-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateMachine.js
More file actions
42 lines (34 loc) · 935 Bytes
/
StateMachine.js
File metadata and controls
42 lines (34 loc) · 935 Bytes
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
class StateMachine {
constructor(states) {
checkStates(states.states);
this.current = states.init;
this.ends = states.ends;
this.states = states.states;
}
get currentState () {
return this.current;
}
get canIEnd() {
return this.ends.includes(this.current)
}
next(value) {
const found = this.states
.find(item => item.value === value && item.from === this.current);
if (!found) {
return false;
}
this.current = found.to;
return true;
}
}
function checkStates(states) {
for (let i = 0; i < states.length; i++) {
for (let j = i + 1; j < states.length; j++) {
if (states[i].from === states[j].from &&
states[i].value === states[j].value) {
throw new Error('This state machine cannot contain contain ' +
'the same value that goes to different states');
}
}
}
}