Skip to content

Instantly share code, notes, and snippets.

@marcoscaceres
Created September 27, 2017 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoscaceres/973d238fc390f6b46a6a50b3e5cca9ee to your computer and use it in GitHub Desktop.
Save marcoscaceres/973d238fc390f6b46a6a50b3e5cca9ee to your computer and use it in GitHub Desktop.
/**
* Implementation of Luhn algorithm.
* Validates ISO/IEC 7812-1 Cards (including credit cards)
*
* @param cardNumber
* @return true, if card is valid.
*/
function luhnCheck(cardNumber) {
const digits = cardNumber.split("").filter(item => !/\s/.test(item));
// The last digit is check digit.
const checkDigit = parseInt(digits.pop());
const sum = digits
// Map them to ints
.map((item, i) => {
const num = parseInt(item);
// Step 1: Double the value of every second digit.
const result = i % 2 ? num : num * 2;
// Split them into single digits
return String(result).split("");
})
// flatten
.reduce((collector, item) => collector.concat(item), [])
// step 2: add them all together
.reduce((collector, item) => parseInt(item) + collector, checkDigit);
// Step 3
return sum % 10 === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment