What you're building
A generic, typed finite-state machine (FSM) β the backbone of traffic lights, game logic, order management, and UI flows. Your FSM will enforce that only valid transitions are accepted, returning an error string when an invalid one is attempted.
Requirements
- Define
StateMachine<S extends string, E extends string>β a class parameterised over a union of state names and a union of event names. - Constructor accepts:
initial: Sβ the starting statetransitions: Array<{ from: S; event: E; to: S }>
getState(): Sβ returns the current state.send(event: E): { ok: true; state: S } | { ok: false; error: string }- If a matching transition exists for
(currentState, event), move totoand return{ ok: true, state: to }. - Otherwise return
{ ok: false, error: "Invalid transition" }.
- If a matching transition exists for
Stretch goals
- Add a
onEntercallback per state, fired whenever that state is entered. - Support
guardpredicates on transitions.
What this proves
You understand generics, discriminated unions, and how to model domain rules as data β all marquee TypeScript skills on any engineering job description.
β‘ 50 XP
solution.tsTranspiled & run in your browser
Loading editorβ¦
Tests4 to pass
starts in initial state
valid transition advances state
invalid transition returns error
full cycle red β green β yellow β red
Run your code to check these.