Created
July 2, 2019 16:16
-
-
Save stefanmaric/8b7be49de22f39132b9137f3081e5dca to your computer and use it in GitHub Desktop.
Luhn Check function in JavaScript for credit card validation
This file contains hidden or 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
const map = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] | |
const luhnCheck = (input) => { | |
const number = String(input).replace(/\D/g, '') | |
let sum = 0 | |
let digit = 0 | |
let i = number.length | |
let even = true | |
while (i) { | |
i -= 1 | |
digit = parseInt(number[i], 10) | |
even = !even | |
sum += even ? map[digit] : digit | |
} | |
return sum > 0 && sum % 10 === 0 | |
} | |
export default luhnCheck |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment