-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.go
55 lines (44 loc) · 1.08 KB
/
db.go
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
52
53
54
55
package banksdb
import "strconv"
// BanksDB is an interface representing the ability to find bank info by creditCard number.
type BanksDB interface {
FindBank(creditCard string) *Bank
}
type banksDBImpl struct {
prefixToBank map[int]*Bank
}
func (b *banksDBImpl) FindBank(creditCard string) *Bank {
// NOTE: Start in reverse order to make less lookups
for _, prefixLength := range []int{6, 5} {
if len(creditCard) < prefixLength {
continue
}
prefix, err := strconv.Atoi(creditCard[:prefixLength])
if err != nil {
return nil
}
if bank, ok := b.prefixToBank[prefix]; ok {
return bank
}
}
return nil
}
func (b *banksDBImpl) addBanksToDB(banks []Bank) {
for i := range banks {
bank := &banks[i]
for _, prefix := range bank.Prefixes {
b.prefixToBank[prefix] = bank
}
}
}
// NewBanksDB creates BanksDB for given countries.
func NewBanksDB(countries ...Country) BanksDB {
banksDB := &banksDBImpl{
prefixToBank: make(map[int]*Bank),
}
for _, country := range countries {
banks := banksByCountry[country]
banksDB.addBanksToDB(banks)
}
return banksDB
}