A lightweight JavaScript finite state machine library.

JSSM is a simple yet powerful finite state machine implementation for JavaScript. It allows you to define states, transitions between them, and actions to execute during transitions.
<scriptsrc="path/to/jssm.min.js"></script>
define(['path/to/JSSM'],function(JSSM){// Your code here});// Create a new state machineconstturnstile=newJSSM({transitions:[// Initial state transition (automatically invoked){name:'init',from:'none',to:'locked'},// Regular transitions{name:'insertCoin',from:'locked',to:'unlocked'},{name:'push',from:'unlocked',to:'locked'}],// Actions to execute during transitionsactions:{init:function(){console.log('Initialized to locked state');},insertCoin:function(info,coin){console.log(`Coin inserted:${coin}`);},push:function(info){console.log('Turnstile pushed');}},// Optional context for actionscontext:null});// Trigger transitionsturnstile.insertCoin(25);// Passes 25 as the coin valueturnstile.push();// Chain transitionsturnstile.insertCoin(25).push().insertCoin(25);
constfsm=newJSSM({// Optional settings_settings:{log:true,// Enable console loggingstrict:false,// Don't throw errors for invalid transitionshistory:false// Don't track transition history},transitions:[// Your transitions here],actions:{// Your actions here}});// Get current stateconstcurrentState=turnstile.current();// or turnstile._current// Get previous stateconstpreviousState=turnstile._previous;// Check if a transition is possibleif(turnstile.can('push')){console.log('Can push the turnstile');}// Check if a transition is not possibleif(turnstile.cannot('insertCoin')){console.log('Cannot insert coin in current state');}The transition info object is always passed as the first argument to action callbacks:
functioninsertCoin(info,coin){console.log(info);// Outputs: { name: 'insertCoin', from: 'locked', to: 'unlocked' }console.log(`Inserted${coin} cents`);}// Allow transition from multiple states{name:'reset',from:['locked','unlocked','broken'],to:'locked'}MIT