forked from jicksta/ranked-pairs-voting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory_store.go
70 lines (57 loc) · 1.67 KB
/
memory_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
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
package trp
import "fmt"
type MemoryStore map[string]*Election
func NewMemoryStore() *MemoryStore {
store := make(MemoryStore)
return &store
}
func (ms *MemoryStore) GetElections() []string {
var result []string
for electionID := range *ms {
result = append(result, electionID)
}
return result
}
func (ms *MemoryStore) GetElection(electionID string) (*Election, error) {
var election, found = (*ms)[electionID]
if !found {
return nil, fmt.Errorf("no election with id %s", electionID)
}
return election, nil
}
func (ms *MemoryStore) CreateElection(electionID string, ballots []*Ballot) (*Election, error) {
election := NewElection(electionID, ballots)
(*ms)[electionID] = election
return election, nil
}
func (ms *MemoryStore) RemoveElection(electionID string) {
delete(*ms, electionID)
}
func (ms *MemoryStore) SaveBallot(electionID string, newBallot *Ballot) (*ElectionResults, error) {
election, err := ms.GetElection(electionID)
if err != nil {
return nil, err
}
var newBallots = []*Ballot{newBallot}
for _, b := range election.Ballots {
if b.VoterID != newBallot.VoterID {
newBallots = append(newBallots, b)
}
}
newElection := NewElection(electionID, newBallots)
(*ms)[electionID] = newElection
results := newElection.Results()
return results, nil
}
func (ms *MemoryStore) RemoveBallot(electionID string, removedVoterID string) (*ElectionResults, error) {
prevElection, _ := ms.GetElection(electionID)
var ballots []*Ballot
for _, b := range prevElection.Ballots {
if b.VoterID != removedVoterID {
ballots = append(ballots, b)
}
}
newElection := NewElection(electionID, ballots)
(*ms)[electionID] = newElection
return newElection.Results(), nil
}