Simple finite state machine in JavaScript

Lightweight, standalone. Less than 0.25 kB. • Source, minified, ZIP, Github

If you simply want to make sure that your application is in a valid state, this is the state machine to use.

The code has no license, it's in the public domain. I do however appreciate attribution.

Grab the complete minified code, just 233 bytes:


fsm.current === ""


Example borrowed from Jake Gordon. Let's create a state machine with a few states and events.

// Ssm( [initial,] events )
var fsm = Ssm("green", // initial is "none" if first parameter is omitted
	{ // events
		warn:  { from: "green",        to: "yellow" },
		panic: { from: "green yellow", to: "red"    }, // allow to be called from multiple states
		calm:  { from: "red",          to: "yellow" },
		clear: {                       to: "green"  }, // if from state is absent, it can be called from all states
		work:  { from: "green"                      } // if to state is absent, the state won't be changed when the event is called

Now we have a simple state machine:

The methods may be used as follows.

// fsm.current === "green"
if (fsm.can("calm"))
	fsm("calm"); // will never happen - can only calm from red

fsm("panic"); // fsm.current === "red"
fsm("warn");  // throws exception! only allowed from green


var fsm = Ssm({ // events
Grouped by from state (switch)
Grouped by to state (switch)