Created
June 19, 2013 18:54
-
-
Save tatat/5816903 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
!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