Last active
July 16, 2019 07:42
-
-
Save Akumzy/b53f8620f3c658655e4f7ad2295aeae7 to your computer and use it in GitHub Desktop.
The Luhn Algorithm in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} digits | |
*/ | |
function luhn(digits) { | |
digits = digits.reverse() | |
for (const index in digits) { | |
if (index % 2) { | |
const doubled = digits[index] * 2 | |
digits[index] = doubled > 9 ? doubled - 9 : doubled | |
} | |
} | |
const sum = digits.reduce((t, c) => t + c, 0) | |
return !(sum % 10) | |
} | |
// https://en.wikipedia.org/wiki/Luhn_algorithm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment