Skip to content

Instantly share code, notes, and snippets.

@Hafthor
Last active August 29, 2015 14:15
Show Gist options
  • Save Hafthor/aa0ea2e5ff3b68a0d3fb to your computer and use it in GitHub Desktop.
Save Hafthor/aa0ea2e5ff3b68a0d3fb to your computer and use it in GitHub Desktop.
calculates Luhn check digit or returns true/false based on if number passes Luhn check (for credit cards, IMEAs, etc)
var luhnMap = ['0246813579','0123456789'];
function luhnCheck(value) {
value = value.replace(/\D/g, '');
return luhnDigit(value.slice(0, -1)) === value.slice(-1);
}
function luhnDigit(value) {
return ('' + value.replace(/\D/g, '').split('').reverse().map(function(d, i) {
return -luhnMap[i % 2][+d];
}).reduce(function(p, n) {
return p + n;
}, value.length * 10)).slice(-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment