Skip to content

Instantly share code, notes, and snippets.

@federicobucchi
Last active August 29, 2015 14:21
Show Gist options
  • Save federicobucchi/57dd2d3c9f8ed71a4a64 to your computer and use it in GitHub Desktop.
Save federicobucchi/57dd2d3c9f8ed71a4a64 to your computer and use it in GitHub Desktop.
Luhn Algorithm - Credit Card Validation
var isValidCreditCard = function (card) {
// Array I want to use to keep the transformed digits
var momentaryCard = [];
// Sum of transformed digits
var sum = 0;
// Card length
var cardLength = card.length;
// Index for loops
var i;
// Parse the card from the end, but from the second-last digit
// Parse going by [i-2] we know we are getting the even digits
// The [i] digits are odd
for (i = cardLength - 2; i >= 0; i = i - 2) {
// Get the even digits and multiple those digits x 2
// 1 * 2, 8 * 2, 3 * 2, 2 * 2, 9 * 2 === 2, 16, 6, 4, 18
momentaryCard.push(card[i] * 2);
// Get the odd digits
// 6 7 9 7 9 4
momentaryCard.push(card[i + 1]);
}
// Add the first value if cardLength is odd
if (cardLength % 2 !== 0) {
momentaryCard.push(card[0]);
}
// Right now the momentaryCard is
// [2, "6", 16, "7", 6, "9", 4, "7", 18, "9", "4"]
// But we want every number separated: 1, 6 and not 16
// ["2", "6", "1", "6", "7", "6", "9", "4", "7", "1", "8", "9", "4"]
momentaryCard = momentaryCard.join('').split('');
// Sum all the values
for (i = 0; i < momentaryCard.length; i++) {
sum += parseInt(momentaryCard[i]);
};
//sum is now === 70
// if this return 0 Luhn passes, divisible by 10 with 0 rest
return sum % 10 === 0;
};
console.log(isValidCreditCard('49927398716'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment