public
Last active

Luhn validation algorithm

  • Download Gist
luhn.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Variant of Avraham Plotnitzky's String.prototype method mixed with the "fast" version
// see: https://sites.google.com/site/abapexamples/javascript/luhn-validation
 
function luhnChk(luhn) {
var len = luhn.length,
mul = 0,
prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
sum = 0;
 
while (len--) {
sum += prodArr[mul][parseInt(luhn.charAt(len), 10)];
mul ^= 1;
}
 
return sum % 10 === 0 && sum > 0;
};

Closure compiled version:
function luhnChk(c){for(var d=c.length,b=0,e=[[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]],a=0;d--;)a+=e[b][parseInt(c.charAt(d),10)],b^=1;return 0===a%10&&0<a};

This is awesome and apparently the most performant luhncheck in js (in chrome at least). Not sure if you have seen this: http://jsperf.com/credit-card-validator/7

wow! awesome! not only fast, but also beautiful code <3
thank you, dude

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.