-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFiniteStateMachine.js
More file actions
42 lines (39 loc) · 1.41 KB
/
FiniteStateMachine.js
File metadata and controls
42 lines (39 loc) · 1.41 KB
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
import { EventDispatcher } from "./EventDispatcher.js";
class FiniteStateMachine extends EventDispatcher {
constructor({
id = "",
initial = "",
transitions = [],
} = {}) {
super();
this.id = id;
this.initial = initial;
this.currentState = initial;
this.graph = {};
this.addTransitions(transitions);
};
addTransitions(transitions) { transitions.forEach(transition => this.addTransition(transition)); };
addTransition({
from, to,
eventName = from + "=>" + to,
} = {}) {
this.graph[from] = this.graph[from] || {};
this.graph[to] = this.graph[to] || {};
this.graph[from][to] = eventName;
};
transition(to, ...data) {
const from = this.currentState;
// console.log(from, "=>", to, this.graph[from]?.[to], data);
if (!(from in this.graph)) return console.error(`FSM: cannot find state "${from}"`);
if (!(to in this.graph)) return console.error(`FSM: cannot find state "${to}"`);
if (!(to in this.graph[from])) return console.error(`FSM: cannot find transition "${from}" => "${to}"`);
const eventName = this.graph[from][to];
this.currentState = to;
this.dispatchEvent(eventName, ...data);
this.dispatchEvent("transitioned", from, to, eventName, ...data);
};
};
export {
FiniteStateMachine,
FiniteStateMachine as FSM,
};