Last active
March 6, 2019 15:03
-
-
Save mfalade/1be269b65d4014c39f2c0ba41c7aecb2 to your computer and use it in GitHub Desktop.
A Javascript implementation of the Luhn Algorithm used for validating credit card numbers.
This file contains 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
const isCardNumberValid = cardNumber => { | |
const normalizedStr = cardNumber.replace(/\s/g, ''); | |
const tokens = Array.from(normalizedStr).map(Number); | |
const checkDigit = tokens.pop(); | |
const nonCheckDigitsSum = tokens | |
.reverse() | |
.reduce((sum, token, i) => { | |
if (!(i % 2)) { | |
const strigifiedDouble = (token * 2).toString(); | |
const s = Array | |
.from(strigifiedDouble) | |
.map(Number) | |
.reduce( | |
(acc, v) => acc + v, 0 | |
); | |
return sum + s; | |
} | |
return sum + token; | |
}, 0); | |
return (nonCheckDigitsSum + checkDigit) % 10 === 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment