-
-
Save agodin3z/73d11b2773901aa8c1e2985b4320bfb7 to your computer and use it in GitHub Desktop.
Luhn algorithm - generate / validate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Luhn = { | |
// length of our number (check digit included) | |
length: 10, | |
pow2: [0, 2, 4, 6, 8, 1, 3, 5, 7, 9], | |
// compute check digit | |
checksum: function (x) { | |
var sum = 0; | |
var n; | |
var odd = false; | |
for (var i = x.length - 1; i >= 0; --i) { | |
n = parseInt(x.charAt(i), 10); | |
sum += odd ? n : this.pow2[n]; | |
odd = !odd; | |
} | |
return sum; | |
}, | |
// validate a number | |
check: function (x) { | |
var clean = String(x).replace(/[^\d]/g, ''); | |
if (clean.length !== this.length) { | |
return false; | |
} | |
var code = clean.substring(0, clean.length - 1); | |
var check = parseInt(clean.substring(clean.length - 1), 10); | |
var checksum = this.checksum(code); | |
return (checksum + check) % 10 === 0; | |
}, | |
// create a random valid number (check digit included at the end) | |
// prefix : if given, our final number will start with prefix (must be a number) | |
generate: function (prefix) { | |
var prefixLength = prefix ? Math.log(prefix) * Math.LOG10E + 1 | 0 : 0; | |
var suffixLength = this.length - 2 - prefixLength; | |
var x = Math.pow(10, suffixLength) + Math.floor(Math.random() * 9 * (Math.pow(10, suffixLength))); | |
x = prefix ? prefix + '' + x : '' + x; | |
var checksum = this.checksum(x) % 10; | |
return checksum === 0 ? x + '0' : x + (10 - checksum); | |
} | |
}; | |
Luhn.check(Luhn.generate()); | |
Luhn.check(Luhn.generate(4972)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment