/
file_system_store.go
45 lines (35 loc) · 942 Bytes
/
file_system_store.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
package main
import (
"encoding/json"
"io"
)
// FileSystemPlayerStore stores players in the filesystem.
type FileSystemPlayerStore struct {
database io.ReadWriteSeeker
}
// GetLeague returns the scores of all the players.
func (f *FileSystemPlayerStore) GetLeague() League {
f.database.Seek(0, io.SeekStart)
league, _ := NewLeague(f.database)
return league
}
// GetPlayerScore retrieves a player's score.
func (f *FileSystemPlayerStore) GetPlayerScore(name string) int {
player := f.GetLeague().Find(name)
if player != nil {
return player.Wins
}
return 0
}
// RecordWin will store a win for a player, incrementing wins if already known.
func (f *FileSystemPlayerStore) RecordWin(name string) {
league := f.GetLeague()
player := league.Find(name)
if player != nil {
player.Wins++
} else {
league = append(league, Player{name, 1})
}
f.database.Seek(0, io.SeekStart)
json.NewEncoder(f.database).Encode(league)
}