A Javascript state machine with a simple API. Well tested, and typed with Flowtype. MIT license.
Specify finite state machines with a brief syntax. Run them. Derive charts from them. Save and load states. Make factories. Impress friends and loved ones. Cure corns and callouses.
const traffic_light = sm`
Red 'Proceed' -> Green 'Proceed' -> Yellow 'Proceed' -> Red;
`;
You could also write that as a piece of data, for when you're generating. That's ... a bit more verbose.
const traffic_light = new jssm.machine({
initial_state : 'Red',
transitions : [
{ action: 'Proceed', from:'Green', to:'Yellow' },
{ action: 'Proceed', from:'Yellow', to:'Red' },
{ action: 'Proceed', from:'Red', to:'Green' }
]
});
In either case, you'll build an executable state machine.
// use with actions
traffic_light.state(); // 'Red'
traffic_light.action('Proceed'); // true
traffic_light.state(); // 'Green'
traffic_light.action('Proceed'); // true
traffic_light.state(); // 'Yellow'
traffic_light.action('Proceed'); // true
traffic_light.state(); // 'Red'
// use with transitions
traffic_light.transition('Yellow'); // false (lights can't go from red to yellow, only to green)
traffic_light.state(); // 'Red'
traffic_light.transition('Red'); // false (lights can't go from red to red, either)
traffic_light.state(); // 'Red'
traffic_light.transition('Green'); // true
traffic_light.state(); // 'Green'
Which you can see being hand-executed in the console here:
There are a lot of state machine impls for JS, many quite a bit more mature than this one. Here are some options:
- Finity 😮
- Stately.js
- machina.js
- Pastafarian
- Henderson
- fsm-as-promised
- state-machine
- mood
- FSM Workbench
- SimpleStateMachine
- shime/micro-machine
- soveran/micromachine (ruby)
- fabiospampinato/FSM
- HQarroum/FSM
- Finite-State-Automata
- finite-state-machine
- nfm
And some similar stuff: