Skip to content

Instantly share code, notes, and snippets.

@mfalade
Last active March 6, 2019 15:03
Show Gist options
  • Save mfalade/1be269b65d4014c39f2c0ba41c7aecb2 to your computer and use it in GitHub Desktop.
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.
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