mini-fsm - A js/NodeJs minimum Finite State Machine (FSM)
Features
- Minimalism, just a single file without any dependency
- Semantics, pure ES6 class based, a fsm is a class definition
- Callbacks support Promise & ES7 async/await
Quick Start
NodeJS version require >= v6
In Node.js you can install mini-fsm with npm:
npm install mini-fsm
A state machine can be defined as a class contains states and transitions, let's create an FSM to represent how traffic light works.
First we should define a fsm as bellow:
;{return'green': {}'yellow': {}'red': {};}{returnturnYellow: from: 'green' to: 'yellow'turnRed: from: 'yellow' to: 'red'turnGreen: from: 'red' to: 'green';}
Then create a traffic light and make it work:
const light = 'green'; //initial state is greenconsole; //output 'green'async {await light;console; //output 'yellow'await light;console; //output 'red'await light;console; //output 'green'};
If state transfer not as expected, an Error will be throw:
const light = 'green';async {tryawait light;catch econsole; //output 'Error: Transition from green to red denied'};