Created
September 27, 2017 08:08
-
-
Save marcoscaceres/973d238fc390f6b46a6a50b3e5cca9ee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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