forked from bigwhite/go-openflights
/
util.go
109 lines (94 loc) · 2.43 KB
/
util.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package openflights
import (
"math"
"strconv"
"strings"
"github.com/StefanSchroeder/Golang-Ellipsoid/ellipsoid"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
var (
geo = ellipsoid.Init("WGS84", ellipsoid.Degrees, ellipsoid.Mile, ellipsoid.LongitudeIsSymmetric, ellipsoid.BearingIsSymmetric)
)
func getAirportByKey(m map[string]*Airport, key string) (*Airport, error) {
airport, ok := m[strings.ToLower(key)]
if !ok {
return nil, grpc.Errorf(codes.NotFound, key)
}
return airport, nil
}
func getAirlineByKey(m map[string]*Airline, key string) (*Airline, error) {
airline, ok := m[strings.ToLower(key)]
if !ok {
return nil, grpc.Errorf(codes.NotFound, key)
}
return airline, nil
}
func getRouteByKey(m map[string]*Route, key string) (*Route, error) {
route, ok := m[strings.ToLower(key)]
if !ok {
return nil, grpc.Errorf(codes.NotFound, key)
}
return route, nil
}
func getRoutesByKeys(m map[string]map[string]map[string][]*Route, airline string, source string, dest string) ([]*Route, error) {
n, ok := m[strings.ToLower(airline)]
if !ok {
return nil, grpc.Errorf(codes.NotFound, airline)
}
o, ok := n[strings.ToLower(source)]
if !ok {
return nil, grpc.Errorf(codes.NotFound, source)
}
routes, ok := o[strings.ToLower(dest)]
if !ok {
return nil, grpc.Errorf(codes.NotFound, dest)
}
return routes, nil
}
func getDistanceForAirports(airport1 *Airport, airport2 *Airport) uint32 {
return getDistance(
float64(airport1.LatitudeMicros)/1000000,
float64(airport1.LongitudeMicros)/1000000,
float64(airport2.LatitudeMicros)/1000000,
float64(airport2.LongitudeMicros)/1000000,
)
}
func getDistance(lat1 float64, lng1 float64, lat2 float64, lng2 float64) uint32 {
distance, _ := geo.To(lat1, lng1, lat2, lng2)
return uint32(round(distance))
}
// expensive
func containsRoute(s []*Route, route *Route) bool {
for _, check := range s {
if route == check {
return true
}
}
return false
}
func containsString(slice []string, s string) bool {
for _, check := range slice {
if s == check {
return true
}
}
return false
}
func parseInt(s string) (int, error) {
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
return int(i), nil
}
func parseFloat(s string, multiplier int) (int, error) {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, err
}
return round(f * float64(multiplier)), nil
}
func round(num float64) int {
return int(num + math.Copysign(0.5, num))
}