-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparallel.go
51 lines (42 loc) · 1.34 KB
/
parallel.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
package statemachine
import (
"errors"
"strings"
)
// Machines bundle up multiple state machine definitions
type Machines map[string]IMachine
// ParallelState describes parallel state machines state
type ParallelState map[string]string
// ParallelSubscribers type declaration for parallel machine subscribers
type ParallelSubscribers []func(ParallelState, ParallelState)
// ParallelMachine to start a parallel state machine
type ParallelMachine struct {
Machines Machines
Subscribers []func(curr, next ParallelState)
}
// Current returns current state of parallel machines
func (m *ParallelMachine) Current() ParallelState {
currentStateMap := make(ParallelState)
for machine := range (*m).Machines {
currentStateMap[machine] = (*m).Machines[machine].Current()
}
return currentStateMap
}
// Transition transitions to next state.
// event format is
// m.Transition("machinekey.eventName")
func (m *ParallelMachine) Transition(event string) (ParallelState, error) {
s := strings.Split(event, ".")
if len(s) != 2 {
return m.Current(), errors.New("event format doesn't match")
}
if _, ok := (*m).Machines[s[0]]; ok {
current := m.Current()
(*m).Machines[s[0]].Transition(s[1])
for _, funct := range (*m).Subscribers {
funct(current, m.Current())
}
return m.Current(), nil
}
return m.Current(), errors.New("machine key doesnot match")
}