Created
September 15, 2017 19:40
-
-
Save ben-bradley/ec0c34eb8478c2bbd50db0129205b365 to your computer and use it in GitHub Desktop.
credit card validator
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
'use strict'; | |
// https://stackoverflow.com/questions/72768/how-do-you-detect-credit-card-type-based-on-number/72801 | |
const validate = (num) => (num | |
.replace(/\D/g, ``) // strip all non-digit chars | |
.split(``) // make an array where each digit is an element | |
.map((n) => Number(n)) // make them all numbers | |
.reverse() // reverse the order | |
.reduce((checksum, n, i) => | |
(i % 2) ? checksum + n : checksum + (n * 2), 0) % 10) === 0; | |
const good = [ | |
`1111 2222 3333 4444`, | |
`1111222233334444`, | |
`1111-2222-3333-4444` | |
].map((n) => ({ n, valid: validate(n) })); | |
const bad = [ | |
`1111 2222 3333 4444 55`, | |
`111122223333444455`, | |
`1111-2222-3333-4444-55` | |
].map((n) => ({ n, valid: validate(n) }));; | |
console.log(`good\n`, good); | |
console.log(`bad\n`, bad); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment