Created
February 27, 2014 09:46
-
-
Save ivoputzer/9247190 to your computer and use it in GitHub Desktop.
Luhn check-digit and validation
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
String.prototype.toLuhn = function() { | |
var sum = 0 | |
this.replace(/\D+/g,'').replace(/[\d]/g, function(c, p, o){ | |
sum += [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]][(o.length-p) & 1][parseInt(c, 10)] | |
}) | |
return this + ((10 - sum % 10) % 10) | |
} | |
String.prototype.isLuhn = function() | |
{ | |
var len = this.length | |
, mul = 0 | |
, sum = 0 | |
while (len--) { | |
sum += [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]][mul][parseInt(this.charAt(len), 10)] | |
mul ^= 1 | |
} | |
return sum % 10 === 0 && sum > 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment