Skip to content

Instantly share code, notes, and snippets.

@Akumzy
Last active July 16, 2019 07:42
Show Gist options
  • Save Akumzy/b53f8620f3c658655e4f7ad2295aeae7 to your computer and use it in GitHub Desktop.
Save Akumzy/b53f8620f3c658655e4f7ad2295aeae7 to your computer and use it in GitHub Desktop.
The Luhn Algorithm in JavaScript
/**
* @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