-
Notifications
You must be signed in to change notification settings - Fork 0
/
decisionmaker.go
50 lines (39 loc) · 1.05 KB
/
decisionmaker.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
package main
import (
"fmt"
"github.com/minisu/ipdip/api"
"github.com/satori/go.uuid"
"math/rand"
"time"
)
type DecisionMaker struct {
repository api.DecisionRepository
}
func NewDecisionMaker(repository api.DecisionRepository) *DecisionMaker {
return &DecisionMaker{repository: repository}
}
func (m *DecisionMaker) createDecision(name string, options []string) (id uuid.UUID, err error) {
id = uuid.NewV4()
err = m.repository.Put(api.Decision{Id: id.String(), Name: name, Options: options})
return
}
func (m *DecisionMaker) decide(id uuid.UUID) (d api.Decision, err error) {
d, err = m.repository.Get(id)
if err != nil {
return
}
if d.DecidedOption != "" {
return d, fmt.Errorf("decision already made")
}
decidedOption := pickRandom(d.Options)
d.DecidedOption = decidedOption
d.DecidedAt = time.Now().UTC()
err = m.repository.Put(d)
return
}
func (m *DecisionMaker) getDecision(id uuid.UUID) (d api.Decision, err error) {
return m.repository.Get(id)
}
func pickRandom(elements []string) string {
return elements[rand.Intn(len(elements))]
}