Skip to content

Machine definition

State machines are defined with a plain object. Properties list of possible states, with values being what state(s) that are possible to change to, or null if no further changes are possible.

An example of a simple state machine is a light switch. It has two states: on and off. When the light is on, the only other state is off. And vice-versa:

{
on: "off",
off: "on"
}

With this machine definition, it would be illegal to have a state dimmed, or to turn it off when it is already off. In this case, the machine never reaches a final state, it can always oscillate between on / off. Note too that we can automatically and reliably advance the state of the machine, because each state indicates what follows.

It’s possible to have several possible next states by using a string array:

{
on: ["off", "half_bright"],
half_bright: ["on", "off"],
off: "on"
}

The example below is intended to start with plain bread, with a few ways of getting to the eventual final state of sprinkled_on_soup or eaten. Once a machine is in its final state, it cannot change to another state unless it is reset.

{
plain: ["toasted", "buttered", "eaten"],
toasted: ["buttered", "eaten", "diced"],
buttered: ["eaten", "marmaladed"],
marmaladed: "eaten",
diced: "sprinkled_on_soup",
sprinkled_on_soup: null,
eaten: null
}