Skip to content

Instantly share code, notes, and snippets.

@ramanathanrv
Created November 19, 2015 13:05
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 ramanathanrv/bcfef0f0e22137ffee3a to your computer and use it in GitHub Desktop.
Save ramanathanrv/bcfef0f0e22137ffee3a to your computer and use it in GitHub Desktop.
Luhn check for cards
/*
* Validate the given card using the Luhn checksum algorithm. Returns `true` if the card
* is valid, else returns `false`.
* Example:
* isCardValid("4242424242424242") // returns true
* isCardValid("4242424242424243") // returns false
*/
var isCardValid = (function (arr) {
return function (ccNum) {
var
len = ccNum.length,
bit = 1,
sum = 0,
val;
while (len) {
val = parseInt(ccNum.charAt(--len), 10);
sum += (bit ^= 1) ? arr[val] : val;
}
return sum && sum % 10 === 0;
};
}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment