-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathluhn.go
More file actions
37 lines (31 loc) · 677 Bytes
/
Copy pathluhn.go
File metadata and controls
37 lines (31 loc) · 677 Bytes
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
package checkdigit
type luhn struct{}
// Verify implements checkdigit.Verifier interface.
func (l luhn) Verify(code string) bool {
if len(code) < 2 {
return false
}
i, err := l.Generate(code[:len(code)-1])
return err == nil && i == int(code[len(code)-1]-'0')
}
// Generate implements checkdigit.Generator interface.
func (l *luhn) Generate(seed string) (int, error) {
if seed == "" {
return 0, ErrInvalidArgument
}
sum, parity := 0, (len(seed)+1)%2
for i, n := range seed {
if isNotNumber(n) {
return 0, ErrInvalidArgument
}
d := int(n - '0')
if i%2 == parity {
d *= 2
if d > 9 {
d -= 9
}
}
sum += d
}
return sum * 9 % 10, nil
}