Skip to content

Instantly share code, notes, and snippets.

@ShirtlessKirk
Last active February 12, 2024 05:09
Show Gist options
  • Save ShirtlessKirk/2134376 to your computer and use it in GitHub Desktop.
Save ShirtlessKirk/2134376 to your computer and use it in GitHub Desktop.
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]));
@jefelewis
Copy link

@ShirtlessKirk What does the array at the end do?

}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]));

@ShirtlessKirk
Copy link
Author

@jefelewis it's a lookup table. Basically, instead of calculating the summed result of the numbers that are doubled (every second digit from right) each time, the code uses the precalculated value stored in the array at the index of the digit in question.

For example, if the digit is 6, the summed double is 3 (6 * 2 = 12, 1 + 2 = 3). In the array, the value at index 6 (the original digit used as a reference) is set to 3.

@bdr193
Copy link

bdr193 commented May 10, 2022

@ShirtlessKirk Can this be implemented in Shopify or Woocommerce? How can you install it without having access to the payment iframe

@carlosvega20
Copy link

Declarative/functional approach:

const checkLuhn = cardNumber => {
    const sum = [...cardNumber].reduceRight((prev, curr, i, arr) =>
        prev+= (i%2)?Number(arr[Number(curr)]):Number(curr)
    ,0);
    return sum && sum % 10 === 0;
}

https://gist.github.com/carlosvega20/8ec8b472de22626a70a65f5893de82e9?permalink_comment_id=4748205#gistcomment-4748205

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment