Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Calculate or verify a Luhn (Mod10) checksum
/**
* Calculate a Luhn (Mod10) checksum
* -or-
* Verify the Luhn checksum of a credit card or IMEI number
*
* This implementation was adapted from the following sources:
* - https://en.wikipedia.org/w/index.php?title=Luhn_algorithm&oldid=688221366
* - https://gist.github.com/ShirtlessKirk/2134376
*/
var luhn = {
/* Calculates the Luhn checksum */
calculate: function(digits) {
var sum = this.sum(digits, false);
return (sum * 9) % 10;
},
/* Verifies if a number is a valid Luhn checksum */
verify: function(digits) {
var sum = this.sum(digits, true);
return sum > 0 && sum % 10 === 0;
},
/* Sum each digit from right to left, and double
every second digit. If the double exceeds 9,
then sum its digits (i.e., 654321 -> 358341
-> 24) */
sum: function(digits, even) {
var sum = 0,
digit = 0,
i = digits.length;
while (i--) {
digit = Number(digits[i]);
sum += (even = !even) ? this.computed[digit] : digit;
}
return sum;
},
/* Create a precomputed list based on doubling
each digit, as described in sum(). */
computed: [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
};
var helpers = {
/* Appends a Luhn checksum to the end of a number */
createLuhnId: function(number) {
var digits = String(number);
return digits + luhn.calculate(digits);
},
/* Checks if a credit card or IMEI number is valid */
isLuhnId: function(number) {
return luhn.verify(String(number));
}
};
@Wintersunner

This comment has been minimized.

Copy link

@Wintersunner Wintersunner commented Jan 18, 2016

Thank you.

@heymartinadams

This comment has been minimized.

Copy link

@heymartinadams heymartinadams commented Sep 29, 2017

Wonderful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment