luhn.ts 712 B

12345678910111213141516171819202122232425
  1. export function valid(digitString: string): boolean {
  2. digitString = digitString.replace(/ /g, '');
  3. if (digitString.length < 2) {
  4. return false;
  5. }
  6. if (digitString.match(/\D/)) {
  7. return false;
  8. }
  9. const len = digitString.length;
  10. const zero = 0x30; // ASCII '0'
  11. let sum = 0;
  12. for (let i = len - 1; i >= 0; i--) {
  13. // We know digit is in [0,9] because we filtered against \D above.
  14. let digit = (digitString.codePointAt(i) ?? zero) - zero
  15. if ((len - i) % 2 == 0) {
  16. digit *= 2;
  17. if (digit > 9) {
  18. digit -= 9;
  19. }
  20. }
  21. sum += digit;
  22. sum %= 10;
  23. }
  24. return sum % 10 === 0;
  25. }