A Typescript implementation of the Luhn algorithm in validating credit card numbers.
/**
* Returns `true` if and only if the given credit card number is valid.
*/
function isLuhnValid2(ccNum: string): boolean {
const chars = [...ccNum];
const sumOfAltDoubles: number = chars.reduce((sumSoFar: number, value: string, index: number) => {
const multiplier = (index % 2 === 0) ? 2 : 1;
let tempValue: number = parseInt(value) * multiplier;
if (tempValue >= 10) {
tempValue = tempValue - 9;
}
return sumSoFar += tempValue;
}, 0);
return (sumOfAltDoubles % 10 === 0);
}
Source of algorithm: https://www.groundlabs.com/blog/anatomy-of-a-credit-card/
Top comments (0)