/
index.js
91 lines (75 loc) · 2.33 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* A very basic and simple finite state machine implementation
*/
'use strict';
const EventEmitter = require('eventemitter3');
const assign = require('xtend/mutable');
module.exports = class FSM extends EventEmitter {
constructor(states) {
super();
this.states = states;
this._current = null;
this._currenAction = null;
this._inExitHandler = false;
if (!states.initial) {
throw new Error('No initial state specified');
}
// add mixins
toArray(arguments, 1).forEach(mixin => assign(this, mixin));
var target = typeof states.initial === 'string' ? states.initial : 'initial';
this.transition(target)
}
get current() {
return this._current;
}
transition(target) {
var curState = this.states[this.current];
var newState = this.states[target];
if (!newState) {
this.emit('invalid-state', target);
return;
}
if (!this._inExitHandler && curState !== newState) {
if (curState && curState._exit) {
this._inExitHandler = true;
curState._exit.call(this);
this._inExitHandler = false;
}
this.emit('transition', {
from: this.current,
to: target,
action: this._currenAction
});
this._current = target;
if (newState._enter) {
newState._enter.call(this);
}
}
}
handle(action) {
var args = toArray(arguments, 1);
var curState = this.states[this.current];
var handler = curState[action] || curState['*'];
if (this._inExitHandler) {
return;
}
var eventPayload = {action, state: this.current};
if (!handler) {
this.emit('no-handler', eventPayload);
return;
}
var result;
this._currenAction = action;
this.emit('handling', eventPayload);
if (typeof handler === 'function') {
result = handler.apply(this, args);
} else {
result = handler;
this.transition(handler);
}
this.emit('handled', eventPayload);
}
}
function toArray(obj, ix) {
return Array.prototype.slice.call(obj, ix || 0);
}