-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart.go
76 lines (63 loc) · 1.13 KB
/
cart.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
package main
import (
"sync"
"sync/atomic"
)
type Carts struct {
data map[int]*Cart
mu sync.RWMutex
}
var currentID = int32(0)
func NewCart() *Cart {
return &Cart{
ID: int(atomic.AddInt32(¤tID, 1)),
}
}
func NewCarts() *Carts {
return &Carts{
data: make(map[int]*Cart),
}
}
func (c *Carts) Add(cart *Cart) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[cart.ID] = cart
}
func (c *Carts) Get(id int) *Cart {
c.mu.RLock()
defer c.mu.RUnlock()
cart, exists := c.data[id]
if !exists {
id := int(atomic.AddInt32(¤tID, 1))
cart = &Cart{
ID: id,
Beers: make([]Beer, 0),
}
c.data[id] = cart
}
return cart
}
// Remove cart by id from carts
func (c *Carts) Remove(id int) {
c.mu.RLock()
defer c.mu.Unlock()
delete(c.data, id)
}
// AddBeer if beer not exists in cart
func (c *Cart) AddBeer(beer Beer) {
for _, b := range c.Beers {
if b.ID == beer.ID {
return
}
}
c.Beers = append(c.Beers, beer)
}
// RemoveBeer if beer exists in cart
func (c *Cart) RemoveBeer(beer Beer) {
for i, b := range c.Beers {
if b.ID == beer.ID {
c.Beers = append(c.Beers[:i], c.Beers[i+1:]...)
return
}
}
}