Skip to content

Instantly share code, notes, and snippets.

@mezerotm
Last active April 15, 2023 14:54
Show Gist options
  • Save mezerotm/a32bfc48ccbd659e210533917023eb7d to your computer and use it in GitHub Desktop.
Save mezerotm/a32bfc48ccbd659e210533917023eb7d to your computer and use it in GitHub Desktop.
In this implementation, the state machine takes an object states that defines the possible states and actions for each input. Each state is a nested object with keys representing the inputs that can trigger a transition to another state. The value of each input key is the name of the destination state, or null if the input should be ignored. The…
class StateMachine {
constructor(states) {
this.states = states;
this.currentState = null;
}
transition(input) {
const nextState = this.states[this.currentState][input];
if (nextState) {
this.currentState = nextState;
this.states[this.currentState].action();
}
}
run(inputs) {
for (const input of inputs) {
this.transition(input);
}
}
}
const states = {
A: {
a: 'B',
b: 'C',
action: () => console.log('State A')
},
B: {
b: 'A',
c: 'C',
action: () => console.log('State B')
},
C: {
a: 'A',
action: () => console.log('State C')
}
};
const machine = new StateMachine(states);
machine.currentState = 'A';
machine.run(['a', 'b', 'c', 'a', 'b']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment