~mendelmaleh/checksum

checksum/luhn.go -rw-r--r-- 742 bytes
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
package checksum

func luhn(i, n, c int) int {
	if i%2 == 0 {
		return c + n
	}

	return c + n*2/10 + n*2%10
}

func getluhn(i, n, c int) int {
	if i%2 == 1 {
		return c + n
	}

	return c + n*2/10 + n*2%10
}

// Luhn checksum validation
func Luhn(num int) bool {
	return IterInt(num*100, luhn)%10 == 0
}

// GetLuhn calculates the Luhn check digit for num.
func GetLuhn(num int) int {
	return IterInt(num*100, getluhn) * 9 % 10
}

// LuhnString checksum validation
func LuhnString(num string) (bool, error) {
	sum, err := IterString(num, luhn)
	return sum%10 == 0, err
}

// GetLuhnString calculates the Luhn check digit for num.
func GetLuhnString(num string) (int, error) {
	sum, err := IterString(num, getluhn)
	return sum * 9 % 10, err
}