## ~mendelmaleh/checksum

checksum/utils.go -rw-r--r-- 1.3 KiB
3c2ecf21Mendel E Luhn optimizations 11 months ago
`                                                                                `
```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```
```package checksum

import (
"fmt"
"math"
)

// IterInt iterates smallest to largest, over each decimal digit in num,
// and sets fn(index, digit, checksum) as the new sum, and returns it.
func IterInt(num int, fn func(i, n, c int) int) (check int) {
for i, n := 0, num; n > 0; i, n = i+1, n/10 {
check = fn(i, n%10, check)
}

return check
}

// IterOppositeInt iterates largest to smallest, over each decimal digit in num,
// and sets fn(index, digit, checksum) as the new sum, and returns it.
func IterOppositeInt(num int, fn func(i, n, c int) int) (check int) {
digits := int(math.Log10(float64(num))) + 1

for i, n := 0, num; i < digits; i++ {
p := int(math.Pow10(digits - i - 1))
check, n = fn(i, n/p, check), n%p
}

return check
}

// IterString iterates over each decimal digit in num,
// and sets fn(index, digit, checksum) as the new sum, and returns it.
func IterString(num string, fn func(i, n, c int) int) (check int, err error) {
for _, r := range num {
if r == ' ' || r == '_' {
continue
}

if r < '0' || '9' < r {
return 0, fmt.Errorf("can't validate %q, invalid rune %c, should be a number", num, r)
}
}

bnum := []byte(num)
var index int
for i := 0; i < len(bnum); i++ {
r := bnum[len(bnum)-i-1]

if r == ' ' || r == '_' {
continue
}

check = fn(index, int(r-'0'), check)
index++
}

return
}
```