-
Notifications
You must be signed in to change notification settings - Fork 5
/
ean.go
67 lines (50 loc) · 1.16 KB
/
ean.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
56
57
58
59
60
61
62
63
64
65
66
67
package ean
import (
"fmt"
"strconv"
)
func Valid(ean string) bool {
return ValidEan8(ean) || ValidEan13(ean) || ValidUpc(ean)
}
func ValidUpc(upc string) bool {
return validCode(upc, 12)
}
func ValidEan8(ean string) bool {
return validCode(ean, 8)
}
func ValidEan13(ean string) bool {
return validCode(ean, 13)
}
func validCode(ean string, size int) bool {
checksum, err := checksum(ean, size)
return err == nil && strconv.Itoa(checksum) == ean[size-1:size]
}
func ChecksumEan8(ean string) (int, error) {
return checksum(ean, 8)
}
func ChecksumEan13(ean string) (int, error) {
return checksum(ean, 13)
}
func ChecksumUpc(upc string) (int, error) {
return checksum(upc, 12)
}
func checksum(ean string, size int) (int, error) {
if len(ean) != size {
return -1, fmt.Errorf("incorrect ean %v to compute a checksum", ean)
}
code := ean[:size-1]
multiplyWhenEven := size%2 == 0
sum := 0
for i, v := range code {
value, err := strconv.Atoi(string(v))
if err != nil {
return -1, fmt.Errorf("contains non-digit: %q", v)
}
if (i%2 == 0) == multiplyWhenEven {
sum += 3 * value
} else {
sum += value
}
}
return (10 - sum%10) % 10, nil
}