-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovince.go
84 lines (67 loc) · 1.81 KB
/
province.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 vnprovince
import "errors"
// ProvincesLength is the number of provinces.
const ProvincesLength = 63
// Province represents a province.
type Province struct {
Code int64 `json:"code"`
Name string `json:"name"`
Districts []District `json:"districts"`
}
// GetProvinces returns all provinces and districts.
func GetProvinces() ([]*Province, error) {
out := make([]*Province, 0, ProvincesLength)
if err := EachProvince(func(p Province) error {
out = append(out, &p)
return nil
}); err != nil {
return nil, err
}
return out, nil
}
// EachProvince iterates over all provinces and districts.
func EachProvince(fn func(p Province) error) error {
if fn == nil {
return errors.New("fn is nil")
}
var previousCode int64 = 1
currentProvince := Province{
Districts: make([]District, 0, districtsCapacity),
}
if err := EachDivision(func(d Division) error {
if previousCode != d.ProvinceCode {
if err := fn(currentProvince); err != nil {
return err
}
// update previousCode
previousCode = d.ProvinceCode
currentProvince.Districts = make([]District, 0, districtsCapacity)
}
provinceFromDivision(&d, ¤tProvince)
return nil
}); err != nil {
return err
}
// handle the last province
if err := fn(currentProvince); err != nil {
return err
}
return nil
}
// provinceFromDivision converts a division to a province.
func provinceFromDivision(d *Division, p *Province) {
p.Code = d.ProvinceCode
p.Name = d.ProvinceName
var currentDistrict *District
for i := range p.Districts {
district := &p.Districts[i]
if district.Code == d.DistrictCode {
currentDistrict = district
}
}
if currentDistrict == nil {
p.Districts = append(p.Districts, District{})
currentDistrict = &p.Districts[len(p.Districts)-1]
}
districtFromDivision(d, currentDistrict)
}