Skip to content

Instantly share code, notes, and snippets.

@orodio
Created August 14, 2015 06:24
Show Gist options
  • Save orodio/23d249ebceb7b299950a to your computer and use it in GitHub Desktop.
Save orodio/23d249ebceb7b299950a to your computer and use it in GitHub Desktop.
function digitalRoot (n) {
return n === 0 ? 0 : 1 + ((n - 1) % 9)
}
function sum (a,b) { return a + b }
function luhn (x) {
return String(x)
.trim()
.split("")
.map(n => parseInt(n, 10))
.reverse()
.map((n,i) => i % 2 ? digitalRoot(n * 2) : n)
.reduce(sum) % 10 === 0
}
function type (x) {
let n = String(x).trim()
switch (true) {
case (/^4[0-9]{12}(?:[0-9]{3})?$/).test(n): return "vi" // Visa
case (/^5[1-5][0-9]{14}$/).test(n): return "mc" // Master Card
case (/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/).test(n): return "dc" // Diners Club
case (/^3[47][0-9]{13}$/).test(n): return "ax" // American Express
case (/^6(?:011|5[0-9]{2})[0-9]{12}$/).test(n): return "dd" // Discover
case (/^1[0-9]{14,15}$/).test(n): return "tp" // uapt
case (/^(?:2131|1800|35\d{3})\d{11}$/).test(n): return "jc" // japan credit bureau
default: return "unknown"
}
}
// Tests
function pad (w, t) {
t = String(t).trim()
let x = 1
while (t.length <= w) {
t = x % 2 ? (t + " ") : (" " + t)
x++
}
return t
}
console.log(`${pad(14, "luhn")} ${pad(18,"type")} ${pad(17,"Number")}`)
console.log(`===============|===================|===================|`)
const good =
[ ["vi", true, 4111111111111111]
, ["vi", true, 4012888888881881]
, ["ax", true, 378282246310005]
, ["dd", true, 6011111111111117]
, ["mc", true, 5105105105105100]
, ["ax", true, '378282246310005']
, ["ax", true, '371449635398431']
, ["ax", true, '378734493671000']
, ["dc", true, '30569309025904']
, ["dc", true, '38520000023237']
, ["vi", true, '4111111111111111']
, ["vi", true, '4012888888881881']
, ["vi", true, '4222222222222']
, ["mc", true, '5555555555554444']
, ["mv", true, '5105105105105100 ']
, ["dd", true, '6011111111111117']
, ["dd", true, '6011000990139424']
, ["mc", false, 5105105105105106]
, ["unknown", false, "bob"]
].forEach(n => console.log(`|${pad(6,n[1])} ${pad(5,luhn(n[2]))}|${pad(8,n[0])} ${pad(8,type(n[2]))}|${pad(18,n[2])}|`))
console.log(`===============|===================|===================|`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment