forked from svicknesh/myschoollist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
school.go
84 lines (69 loc) · 2.17 KB
/
school.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 myschoollist
import (
"encoding/json"
"os"
"path/filepath"
"strings"
)
// School - information about a school in Malaysia
type School struct {
ID int `json:"id"`
Name string `json:"name"`
SchoolCode string `json:"schoolcode"`
Level string `json:"level"`
Address string `json:"address"`
Postcode int `json:"postcode"`
City string `json:"city"`
EMail string `json:"email"`
CoordinateXX float64 `json:"coordinatexx"`
CoordinateYY float64 `json:"coordinateyy"`
DisrictID int `json:"district_id"` // references the district this school is in
}
// schools - slice of schools in Malaysia and important mappings
type schools struct {
items []School
mapSchoolID map[int]int
mapSchoolCode map[string]int
mapSchoolDistrict map[int][]int
}
// newSchools - creates new instance of Schools with proper mapping
func newSchools(jsonDir string) (schoolsV *schools, err error) {
schoolsV = new(schools)
file, err := os.Open(filepath.Join(jsonDir, "school.json"))
if err != nil {
return
}
defer file.Close()
err = json.NewDecoder(file).Decode(&schoolsV.items)
if nil != err {
return
}
schoolsV.mapSchoolID = make(map[int]int)
schoolsV.mapSchoolCode = make(map[string]int)
schoolsV.mapSchoolDistrict = make(map[int][]int)
// we map the slice index to a map for quicker access intead of looping through the slice one by one
for index, school := range schoolsV.items {
schoolsV.mapSchoolID[school.ID] = index
schoolsV.mapSchoolCode[school.SchoolCode] = index
schoolsV.mapSchoolDistrict[school.DisrictID] = append(schoolsV.mapSchoolDistrict[school.DisrictID], school.ID)
}
return
}
// GetByID - returns school information given its id
func (schools *schools) GetByID(id int) (school School, found bool) {
index, found := schools.mapSchoolID[id]
if !found {
return
}
school = schools.items[index]
return
}
// GetByCode - returns school information given its code
func (schools *schools) GetByCode(schoolcode string) (school School, found bool) {
index, found := schools.mapSchoolCode[strings.ToUpper(schoolcode)]
if !found {
return
}
school = schools.items[index]
return
}