Comparing various implementations of the Luhn algorithm.
function luhn(input) {
const precomputed = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
let sum = 0;
let isSecond = 0;
let length = input.length;
while (length) {
const num = input.charCodeAt(--length) - 48;
sum += isSecond ? precomputed[num] : num;
isSecond ^= 1;
}
return sum % 10 === 0;
}
function isLuhnAlgo(digits) {
let length = digits.length;
let bit = 1;
let sum = 0;
while (length) {
const value = +digits[--length];
bit ^= 1;
sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;
}
return sum % 10 === 0;
}
Initializing...
| Test Case | Ops/sec | |
|---|---|---|
| luhn() | | ready |
| isLuhnAlgo() | | ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.