-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateMachine.js
72 lines (67 loc) · 1.75 KB
/
StateMachine.js
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
71
72
function createMachine(stateMachineDefinition) {
const machine = {
value: stateMachineDefinition.initialState,
performTransition(currentState, event) {
// currentstate event newstate
const currentStateDefinition = stateMachineDefinition[currentState];
const destinationTransition = currentStateDefinition.transitions[event];
if (!destinationTransition) {
return;
}
const destinationState = destinationTransition.target;
const destinationStateDefinition =
stateMachineDefinition[destinationState];
destinationTransition.action();
currentStateDefinition.actions.onExit();
destinationStateDefinition.actions.onEnter();
machine.value = destinationState;
return machine.value;
},
};
return machine;
}
const machine = createMachine({
initialState: "off",
off: {
actions: {
onEnter() {
console.log("off: onEnter");
},
onExit() {
console.log("off: onExit");
},
},
transitions: {
switch: {
target: "on",
action() {
console.log('transition action for "switch" in "off" state');
},
},
},
},
on: {
actions: {
onEnter() {
console.log("on: onEnter");
},
onExit() {
console.log("on: onExit");
},
},
transitions: {
switch: {
target: "off",
action() {
console.log('transition action for "switch" in "on" state');
},
},
},
},
});
let state = machine.value;
console.log(`current state: ${state}`);
state = machine.performTransition(state, "switch");
console.log(`current state: ${state}`);
state = machine.performTransition(state, "switch");
console.log(`current state: ${state}`);