-
Notifications
You must be signed in to change notification settings - Fork 0
/
beer.go
52 lines (46 loc) · 859 Bytes
/
beer.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
package main
import (
"sort"
"sync"
)
type Beers struct {
beers []Beer
mu sync.Mutex
}
// sort beers by id
func (beers *Beers) Len() int {
beers.mu.Lock()
defer beers.mu.Unlock()
return len(beers.beers)
}
func (beer *Beers) Less(i, j int) bool {
beer.mu.Lock()
defer beer.mu.Unlock()
return beer.beers[i].ID < beer.beers[j].ID
}
func (beer *Beers) Swap(i, j int) {
beer.mu.Lock()
defer beer.mu.Unlock()
beer.beers[i], beer.beers[j] = beer.beers[j], beer.beers[i]
}
func NewBeers(beers []Beer) *Beers {
return &Beers{
beers: beers,
}
}
func (bs *Beers) GetRemains() []Beer {
bs.mu.Lock()
defer bs.mu.Unlock()
sort.Sort(bs)
return bs.beers
}
func (bs *Beers) GetByID(id int) (*Beer, bool) {
bs.mu.Lock()
defer bs.mu.Unlock()
for _, beer := range bs.beers {
if beer.ID == id {
return &beer, true
}
}
return nil, false
}