Explorer
Node.js

Implement a `createStateMachine(config)` where config defines states and transitions. Returns `{ getState(), transition(event) }`.

Problem Statement

Implement a `createStateMachine(config)` where config defines states and transitions. Returns `{ getState(), transition(event) }`.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: A state machine has a current state and defined transitions between states. šŸ’” Hint 2: Config should have initial state and transitions: { initial, transitions: { EVENT: { from: "stateA", to: "stateB" } } }. šŸ’” Hint 3: transition() checks if the event is valid from the current state, then changes state. āœ… Solution: ```javascript function createStateMachine(config) { let state = config.initial; return { getState() { return state; }, transition(event) { const t = config.transitions[event]; if (!t) throw new Error(`Unknown event: ${event}`); if (t.from !== state) throw new Error(`Cannot ${event} from ${state}`); state = t.to; return state; } }; } ```

State Machine

Hard
Implement a `createStateMachine(config)` where config defines states and transitions. Returns `{ getState(), transition(event) }`.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"state":"paused"}