isLuhnValid.js 942 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = isLuhnValid;
  6. var _assertString = _interopRequireDefault(require("./util/assertString"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8. function isLuhnValid(str) {
  9. (0, _assertString.default)(str);
  10. var sanitized = str.replace(/[- ]+/g, '');
  11. var sum = 0;
  12. var digit;
  13. var tmpNum;
  14. var shouldDouble;
  15. for (var i = sanitized.length - 1; i >= 0; i--) {
  16. digit = sanitized.substring(i, i + 1);
  17. tmpNum = parseInt(digit, 10);
  18. if (shouldDouble) {
  19. tmpNum *= 2;
  20. if (tmpNum >= 10) {
  21. sum += tmpNum % 10 + 1;
  22. } else {
  23. sum += tmpNum;
  24. }
  25. } else {
  26. sum += tmpNum;
  27. }
  28. shouldDouble = !shouldDouble;
  29. }
  30. return !!(sum % 10 === 0 ? sanitized : false);
  31. }
  32. module.exports = exports.default;
  33. module.exports.default = exports.default;