-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathisisbn.go
84 lines (66 loc) · 1.38 KB
/
isisbn.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package validatorgo
import (
// "fmt"
"strconv"
)
// A validator that checks if the string is an [ISBN].
//
// version: ISBN version to compare to. Accepted values are "10" and "13". If none provided, both will be tested.
//
// ok := validatorgo.IsISBN("0-7167-0344-0", "10")
// fmt.Println(ok) // true
// ok := validatorgo.IsISBN("0-7168-0344-0", "10")
// fmt.Println(ok) // false
//
// [ISBN]: https://en.wikipedia.org/wiki/ISBN
func IsISBN(str, version string) bool {
strNum := stripDashesAndSpaces(str)
if version == "10" {
return valIsISBNv10(strNum)
} else if version == "13" {
return valIsISBNv13(strNum)
} else {
return valIsISBNv10(strNum) || valIsISBNv13(strNum)
}
}
func valIsISBNv10(str string) bool {
ln := len(str)
sum := 0
if ln != 10 {
return false
}
for i, char := range str {
pos := ln - i
num, err := strconv.Atoi(string(char))
if err != nil {
return false
}
sum += pos * num
}
rem := sum % 11
return rem == 0
}
func valIsISBNv13(str string) bool {
ln := len(str)
sum := 0
if ln != 13 {
return false
}
for i, char := range str {
pos := ln - i
num, err := strconv.Atoi(string(char))
if err != nil {
return false
}
if pos%2 == 0 {
sum += 3 * num
// fmt.Printf("3 * %d\n", num)
} else {
sum += 1 * num
// fmt.Printf("1 * %d\n", num)
}
}
// fmt.Println("Sum is", sum)
rem := sum % 10
return rem == 0
}