-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
84 lines (68 loc) · 1.72 KB
/
service.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 eta
import (
"errors"
)
type EtaService struct {
limitCars int
apiRequest ApiRequester
}
var (
ErrFetchCarsPositions = errors.New("couldn't fetch cars positions")
ErrEmptyCarsPositions = errors.New("empty cars positions")
ErrFetchEtas = errors.New("couldn't fetch etas")
ErrEmptyEtas = errors.New("empty etas")
ErrInternal = errors.New("couldn't detect min ETA")
)
var (
defaultLimitCars = 100
)
func NewEtaService(apiRequest ApiRequester) *EtaService {
return &EtaService{limitCars: defaultLimitCars, apiRequest: apiRequest}
}
func (s *EtaService) FindMinEta(targetPosition Position) (Eta, error) {
positions, err := s.getCarPositions(targetPosition)
if err != nil {
return 0, err
}
if len(positions) == 0 {
return 0, ErrEmptyCarsPositions
}
etas, err := s.getEtas(targetPosition, positions)
if err != nil {
return 0, err
}
if len(etas) == 0 {
return 0, ErrEmptyEtas
}
minEta, err := s.min(etas)
if err != nil {
return 0, ErrInternal
}
return minEta, nil
}
func (s *EtaService) getEtas(position Position, carsPositions []Position) ([]Eta, error) {
resp, err := s.apiRequest.FetchEtas(position, carsPositions)
if err != nil {
return resp, ErrFetchEtas
}
return resp, nil
}
func (s *EtaService) getCarPositions(position Position) ([]Position, error) {
resp, err := s.apiRequest.FetchCarPositions(position, s.limitCars)
if err != nil {
return resp, ErrFetchCarsPositions
}
return resp, err
}
func (s *EtaService) min(values []Eta) (Eta, error) {
if len(values) == 0 {
return 0, errors.New("cannot detect a minimum value in an empty slice")
}
minValue := values[0]
for _, v := range values {
if v < minValue {
minValue = v
}
}
return minValue, nil
}