-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfsm.go
54 lines (44 loc) · 1.03 KB
/
fsm.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
package fsm
type FSM struct {
state stateType
states []stateType
initial stateType
events map[eventType]*Event
}
func (fsm *FSM) DefineStates(states ...stateType) {
if len(states) == 0 {
panic("need to have atleast one state")
}
fsm.initial = states[0]
fsm.state = fsm.initial
fsm.states = states
}
func (fsm *FSM) Hydrate(currentState stateType) {
var validState bool
for _, state := range fsm.states {
if currentState == state {
validState = true
break
}
}
if !validState {
panic("cannot hydrate with an undefined state")
}
fsm.state = currentState
}
func (fsm *FSM) State() stateType {
return fsm.state
}
func (fsm *FSM) On(eventName eventType, registrationFn func(event *Event)) {
newEvent := newEvent(fsm)
registrationFn(newEvent)
fsm.events[eventName] = newEvent
}
func (fsm *FSM) Fire(eventName eventType, eventArgs ...any) (stateType, error) {
return fsm.events[eventName].fire(eventArgs...)
}
func New() *FSM {
return &FSM{
events: map[eventType]*Event{},
}
}