-
Notifications
You must be signed in to change notification settings - Fork 19
/
card.js
51 lines (42 loc) · 1.04 KB
/
card.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict'
const luhn = require('fast-luhn')
const Types = require('./types')
module.exports = Card
function Card (data) {
const types = Types(data)
return {
types: data,
parse: parseCard,
format: formatCard,
type: cardType,
luhn: luhn,
isValid: isCardValid
}
function parseCard (number) {
if (typeof number !== 'string') return ''
return number.replace(/[^\d]/g, '')
}
function formatCard (number, separator) {
const type = getType(number, true)
if (!type) return number
return type.group(number).join(separator || ' ')
}
function cardType (number, eager) {
const type = getType(number, eager)
return type ? type.name : undefined
}
function isCardValid (number, type) {
if (type) {
type = types.get(type)
} else {
type = getType(number)
}
if (!type) return false
return (!type.luhn || luhn(number)) && type.test(number)
}
function getType (number, eager) {
return types.find(function (type) {
return type.test(number, eager)
})
}
}