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;
}
};
}
```