Synchronous finite state machine
A synchronous FSM that also triggers events when entering or leaving a state.
Installation
npm install synchronous-fsm
How to use
Require synchronous-fsm:
var FSM = require("synchronous-fsm");
To initialize the statemachine we need to define states and transitions first:
var states = {
"opened": [
["pass", function onPass(event) {
passCalled = event;
}, "closed"],
["coin", function onCoin(event) {
console.log("thanks");
}]
],
"closed": [
["coin", function coin(event) {
coinCalled = event;
}, "opened"]
]
};
Then we can initialize the state machine in the desired state:
var fsm = new FSM("opened", states);
Trigger a transition:
fsm.event("pass");
fsm.event("pass", "6km/h", "8:30pm");
Get the current state:
fsm.getCurrent();
Can also be directly advanced to a given state:
fsm.advance("closed");
The stateMachine also triggers an "entry" and an "exit" event when entering and leaving a state. Simply add the handlers like for any other event:
var states = {
"opened": [
...
["entry", function onEntry(event) {
console.log("entering state...");
}],
["exit", function onExit(event) {
console.log("leaving state...");
}],
],
"closed": [
...
]
};
LICENSE
MIT