Build a Finite State Machine
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write createMachine(config), where config is { initial, states }: initial names the starting state, and states maps each state's name to an object whose optional on maps event types to transitions. A transition is either a target state's name or an object { target, guard, action }, where guard and action are optional functions. Return a machine with a state property, the current state's name, and send(event), where event is { type, ...anything else } or just a type string, which means { type }. If the current state has no transition for the type, or the transition has a guard and guard(event) returns a falsy value, ignore the event and return false. Otherwise move to target, then call action(event) if there is one, and return true. createMachine throws an Error with the message "Unknown state: name" if initial or any target isn't a state in states. Each machine keeps its own state.
Your code must pass
- Starts in the initial state
- Moves to the target on a matching event
- Ignores events the current state doesn't handle
- Blocks a transition when its guard says no
- Runs a transition's action after the state changes
- Throws for an unknown state in the config