Last active
August 27, 2024 05:35
-
-
Save ShirtlessKirk/2134376 to your computer and use it in GitHub Desktop.
Luhn validation algorithm
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
/** | |
* 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])); |
@carlosvega20 I'm a bit confused by Number(arr[Number(curr)])
expression and not sure if this works correctly for check
Can suggest instead smth like this:
const isLuhn = (cardNumber) => {
const checkSum = [...cardNumber].reduceRight((prev, curr, i, arr) => {
if(i % 2) {
return prev += Number(curr);
} else {
const d = Number(curr) * 2
return prev += d > 9 ? d - 9 : d
}
}, 0);
return checkSum && checkSum % 10 === 0
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Declarative/functional approach:
https://gist.github.com/carlosvega20/8ec8b472de22626a70a65f5893de82e9?permalink_comment_id=4748205#gistcomment-4748205