Skip to content

Instantly share code, notes, and snippets.

@Toheeb
Created July 16, 2019 10:32
Show Gist options
  • Save Toheeb/71fa32c7b62933175d902410c0b884ea to your computer and use it in GitHub Desktop.
Save Toheeb/71fa32c7b62933175d902410c0b884ea to your computer and use it in GitHub Desktop.
Here's the Luhn algorithm that takes an array of 16 digits to verify a valid credit card
const validateWithLuhn = (digits) => {
//console.log("digits are: ", digits);
let result = false;
if (/^\d{16}$/.test(digits.join("")) == false) {
//console.log('should be 16 hence false');
return false;
}
const step = 2;
let cummulative = 0;
for( i=15; i >= 0; i--) {
if (i % 2 == 0) {
//console.log('luhn: ', digits[i]);
const luhnValue = digits[i] * 2;
if (luhnValue > 9) {
cummulative += luhnValue - 9;
} else {
cummulative += luhnValue;
}
} else {
//console.log('not luhn: ', digits[i])
cummulative += digits[i];
}
}
//console.log('Cummulative: ', cummulative);
if (cummulative % 10 == 0) {
result = true;
}
//console.log("Result: ", result);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment