javascript / expert
Snippet
State Machine Execution Engine via Generator Control Flow
Generators can serve as synchronous state machines by delegating control flow back to the caller using yield. Passing values into iterator.next(input) feeds data back into the generator function, enabling predictable, zero-dependency finite state machine transitions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function* stateMachine(initialState, transitions) {let currentState = initialState;while (currentState !== 'TERMINATED') {const input = yield currentState;const nextState = transitions[currentState]?.[input];if (!nextState) {throw new Error(`Invalid transition from ${currentState} with input ${input}`);}currentState = nextState;}return currentState;}const transitions = {IDLE: { START: 'RUNNING' },RUNNING: { PAUSE: 'PAUSED', STOP: 'TERMINATED' },PAUSED: { RESUME: 'RUNNING', STOP: 'TERMINATED' }};const engine = stateMachine('IDLE', transitions);console.log(engine.next().value); // IDLEconsole.log(engine.next('START').value); // RUNNINGconsole.log(engine.next('PAUSE').value); // PAUSED
nodejs
Breakdown
1
function* stateMachine(initialState, transitions) {
Defines a generator function that initializes control flow state logic.
2
const input = yield currentState;
Yields current state to the caller and waits for input sent via next(input).
3
const nextState = transitions[currentState]?.[input];
Evaluates state transition mapping based on incoming input signal.