Code

< 40 %
40-60 %
> 60 %
1
package hkid
2
3
import (
4
	"regexp"
5
	"strconv"
6
	"strings"
7
)
8
9
func clearString(s string) string {
10 1
	newString := strings.Trim(s, " ")
11 1
	newString = strings.ToUpper(newString)
12 1
	return newString
13
}
14
15
func getRemainder(hkid *hkid) string {
16 1
	charSum := getCharSum(hkid.part1)
17 1
	hkidSum := calPart2Remainder(hkid.part2, charSum)
18
19 1
	remainder := ""
20
21 1
	switch hkidSum {
22
	case 11:
23 1
		remainder = "0"
24
	case 10:
25 1
		remainder = "A"
26
	default:
27 1
		remainder = strconv.Itoa(hkidSum)
28
	}
29
30 1
	return remainder
31
}
32
33
func calPart2Remainder(s string, i int) int {
34 1
	sum := 0
35
36 1
	for k, v := range s {
37 1
		i, _ := strconv.Atoi(string(v))
38 1
		sum += (7 - k) * i
39
	}
40
41 1
	mod := 11
42 1
	return mod - ((i + sum) % mod)
43
}
44
45
func getCharSum(part1 string) int {
46 1
	charMap := getCharMap()
47 1
	if len(part1) == 1 {
48 1
		return 324 + charMap[part1]*8
49
	}
50
51 1
	total := 0
52 1
	weight := getWeight()
53 1
	for k, v := range part1 {
54 1
		total += weight[k] * charMap[string(v)]
55
	}
56 1
	return total
57
}
58
59
func getWeight() map[int]int {
60 1
	weight := make(map[int]int)
61 1
	weight[0] = 9
62 1
	weight[1] = 8
63 1
	return weight
64
}
65
66
func getCharMap() map[string]int {
67 1
	asciiNum := 65 // Uppercase A
68 1
	idCharMap := make(map[string]int)
69
70 1
	for i := 0; i <= 26; i++ {
71 1
		idCharMap[string(i+asciiNum)] = 10 + i
72
	}
73
74 1
	return idCharMap
75
}
76
77
func validatePatten(string string) (*hkid, error) {
78 1
	r, _ := regexp.Compile(`^(?P<p1>\D{1,2})(?P<p2>\d{6})\((?P<p3>[\w{1}0-9aA])\)$`)
79 1
	match := r.FindStringSubmatch(string)
80 1
	if len(match) == 0 {
81 1
		return newHkidNil(), newPatterNotMatchError()
82
	}
83 1
	return newHkid(match[1], match[2], match[3]), nil
84
}
85