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:
fsm("warn")
, fsm("panic")
, fsm("calm")
, fsm("clear")
, and fsm("work")
throw
an exception if the event is not allowed.fsm.can("warn")
, fsm.can("panic")
, fsm.can("calm")
, fsm.can("clear")
, fsm.can("work")
true
if the <event>
is allowed, else false
.fsm.current
green
.fsm.events
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