HardPro challengePythonJavaScriptTypeScript

Finite State Machine

PatternsState MachinesObjects

Implement createFSM({ initial, transitions }) where:

  • initial — starting state name (string).
  • transitions{ [state]: { [event]: nextState } }.
  • Returns an object with:

- state — current state.
- send(event) — transition; throw if invalid transition.
- can(event) — boolean, whether the event is valid now.

solve(config, events) drives the FSM and returns state history.

Sample tests

Test #1Turnstile FSM
Input: [{"initial":"locked","transitions":{"locked":{"coin":"unlocked"},"unlocked":{"coin":"unlocked","push":"locked"}}},["coin","push","push"]]
Output: ["locked","unlocked","locked","ERROR"]
Test #2Traffic light-like FSM happy path
Input: [{"initial":"idle","transitions":{"idle":{"start":"running"},"paused":{"stop":"idle","resume":"running"},"running":{"stop":"idle","pause":"paused"}}},["start","pause","resume","stop"]]
Output: ["idle","running","paused","running","idle"]
Test #3Simple toggle FSM
Input: [{"initial":"off","transitions":{"on":{"toggle":"off"},"off":{"toggle":"on"}}},["toggle","toggle","toggle"]]
Output: ["off","on","off","on"]
Test #4Invalid event throws, captured as ERROR
Input: [{"initial":"idle","transitions":{"idle":{"start":"running"}}},["invalid"]]
Output: ["idle","ERROR"]
Test #5Terminal state has no transitions
Input: [{"initial":"a","transitions":{"a":{"go":"b"},"b":{"go":"c"},"c":{}}},["go","go","go"]]
Output: ["a","b","c","ERROR"]