Skip to content

Instantly share code, notes, and snippets.

@ben-bradley
Created September 15, 2017 19:40
Show Gist options
  • Save ben-bradley/ec0c34eb8478c2bbd50db0129205b365 to your computer and use it in GitHub Desktop.
Save ben-bradley/ec0c34eb8478c2bbd50db0129205b365 to your computer and use it in GitHub Desktop.
credit card validator
'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