Skip to content

Instantly share code, notes, and snippets.

@tatat
Created June 19, 2013 18:54
Show Gist options
  • Save tatat/5816903 to your computer and use it in GitHub Desktop.
Save tatat/5816903 to your computer and use it in GitHub Desktop.
!function() {
var Luhn = {};
Luhn.valid = function(value) {
value = '' + value;
return this.generate(value.slice(- value.length, -1)) === value;
};
Luhn.generate = (function() {
var table = (function() {
var t = {};
for (var i = 0, j = 9 * 2; i <= j; i ++)
t[i] = i > 9 ? i - 9 : i;
return t;
})();
var re = /^[0-9]+$/;
return function(n) {
if (!re.test(n))
return null;
n = '' + n;
var value = (n + '0')
.split('')
.reverse()
.reduce(function(previous, current, index) {
return previous + table[current * (1 * ((index & 1) + 1))];
}, 0);
return n + ((10 - (value % 10)) % 10);
}
})();
this.Luhn = Luhn;
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment