function luhn(cardNumber) {
sum=0;
for(i=cardNumber.length-1;i>=0;i--) {
sum+=parseInt(cardNumber[i],10);
doubled=parseInt(cardNumber[--i],10)<<1;
sum+=doubled>9 ? doubled-9 : doubled;
}
return sum!=0 && sum%10==0;
}
sum=0;
for(i=cardNumber.length-1;i>=0;i--) {
sum+=parseInt(cardNumber[i],10);
doubled=parseInt(cardNumber[--i],10)<<1;
sum+=doubled>9 ? doubled-9 : doubled;
}
return sum!=0 && sum%10==0;
}
The function assumes you pass in just a string of digits, no hyphens or any of that. In case the one line is confusing, most compilers will optimize an instruction like x*2 to do x<<1 instead, but I'm assuming javascript probably doesn't do that so I did it manually; it just doubles the number. You could get really crazy with the optimization, like changing parseInt(cardNumber[i],10) to cardNumber[i]-'0', but that's probably excessive.
1 comment:
Yes a nice succinct piece of code. I just added these 2 lines to provide a complete solution:
cardNumber=cardNumber.replace(/\s+/g,''); // remove white space
if (!/^\d{15,16}$/.test(cardNumber))return false; // allow 15 or 16 digits only
Post a Comment