-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdatabase_test.go
96 lines (85 loc) · 1.71 KB
/
database_test.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
package karmabot
import (
"sort"
"time"
"github.com/kamaln7/karmabot/database"
)
type TestDatabase struct {
records []database.Points
}
func (t *TestDatabase) InsertPoints(points *database.Points) error {
t.records = append(t.records, *points)
return nil
}
func (t *TestDatabase) GetUser(name string) (*database.User, error) {
foundUser := false
pointCount := 0
for _, r := range t.records {
if r.To == name {
foundUser = true
pointCount += r.Points
}
}
if !foundUser {
return nil, database.ErrNoSuchUser
}
return &database.User{
Name: name,
Points: pointCount,
}, nil
}
func (t *TestDatabase) GetLeaderboard(limit int) (database.Leaderboard, error) {
us := make(map[string]*database.User)
for _, r := range t.records {
u := us[r.To]
if u == nil {
u = &database.User{}
}
u.Points += r.Points
us[r.To] = u
}
lb := make(database.Leaderboard, 0, len(us))
for _, u := range us {
lb = append(lb, u)
}
sort.SliceStable(lb, func(i, j int) bool {
ui := lb[i]
uj := lb[j]
if ui.Points == uj.Points && ui.Name < uj.Name {
return true
}
if ui.Points < uj.Points {
return true
}
return false
})
return lb[:limit], nil
}
func (t *TestDatabase) GetTotalPoints() (int, error) {
totalPoints := 0
for _, r := range t.records {
p := r.Points
if p < 0 {
p = -p
}
totalPoints += p
}
return totalPoints, nil
}
func (t *TestDatabase) GetThrowback(user string) (*database.Throwback, error) {
foundUser := false
var points database.Points
for _, r := range t.records {
if r.To == user {
foundUser = true
points = r
}
}
if !foundUser {
return nil, database.ErrNoSuchUser
}
return &database.Throwback{
Points: points,
Timestamp: time.Now(),
}, nil
}