Skip to content

@ShirtlessKirk /luhn.js
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Luhn validation algorithm
/**
* Luhn algorithm in JavaScript: validate credit card number supplied as string of numbers
* @author ShirtlessKirk. Copyright (c) 2012.
* @license WTFPL (http://www.wtfpl.net/txt/copying)
*/
var luhnChk = (function (arr) {
return function (ccNum) {
var
len = ccNum.length,
bit = 1,
sum = 0,
val;
while (len) {
val = parseInt(ccNum.charAt(--len), 10);
sum += (bit ^= 1) ? arr[val] : val;
}
return sum && sum % 10 === 0;
};
}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]));
@ShirtlessKirk

Closure compiled version (updated Feb 11, 2015):

var luhnChk=function(a){return function(c){for(var l=c.length,b=1,s=0,v;l;)v=parseInt(c.charAt(--l),10),s+=(b^=1)?a[v]:v;return s&&0===s%10}}([0,2,4,6,8,1,3,5,7,9]);
@parris

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

@ondrek

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

@storytime

Awesome!

@MohamedAlaa

Woww! So far the Fastest Algorithm i've tried! :+1:

@oPorks

Well done!

@lagden

Fuckk Yeahhh!!!

@ShirtlessKirk

Spot of code golf: After reviewing subsequent edits on jsperf, I've tweaked the code. The test case is at http://jsperf.com/credit-card-validator/16 if you want to check.

  • decrement now happens inline rather than during the while conditional check (I prefer that placement)
  • reduction of product array contents to just the doubled number value as you've already got the undoubled value (less to initialise, less to look up)
  • the use of a closure to use the product array as a parameter was intriguing
  • return statement reversed to utilise short-circuiting better (if a zero length string is sent in then the sum is 0, cosmetic really)

A variant on the jsperf page doesn't run parseInt() if using the undoubled value. Personally, I don't like using it in some places and not others so I always run it. That's why this code isn't the fastest...

@ChadReitsma

Ummm, WOW. TY!!!!

@lebiru

+1 thanks!

@alesch

@geniuscarpi: Use it as luhnChk("numberToValidate").

@tomByrer

I'm a bit confused the reason for bit ^= 1, since it seems that bit never changes? (version Feb 11, 2015)

@jlukic

Using an adapted version of your luhn check in our validation
Semantic-Org/Semantic-UI@2769a6e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.