Skip to content

Instantly share code, notes, and snippets.

@mezerotm
Last active April 15, 2023 14:54
Show Gist options
  • Save mezerotm/6fb14f5b67beaa6d9bc1264075de15fc to your computer and use it in GitHub Desktop.
Save mezerotm/6fb14f5b67beaa6d9bc1264075de15fc to your computer and use it in GitHub Desktop.
This code defines a state machine with four states: InitialState, State1, State2, and State3. Each state has a set of possible transitions based on the input received. The code also defines a set of actions that can be executed based on the input received. The `nextState` function takes an input, executes the appropriate action, and transitions …
const stateMachine = (inputs) => {
let currentState = "InitialState";
const actions = {
Action1: () => {
// action code for Action1
console.log("Action1 executed");
},
Action2: () => {
// action code for Action2
console.log("Action2 executed");
},
Action3: () => {
// action code for Action3
console.log("Action3 executed");
},
DefaultAction: () => {
// default action code
console.log("DefaultAction executed");
},
};
const transitions = {
InitialState: {
Action1: "State1",
Action2: "State2",
Action3: "State3",
DefaultAction: "InitialState",
},
State1: {
Action1: "State2",
Action2: "State3",
Action3: "InitialState",
DefaultAction: "State1",
},
State2: {
Action1: "State3",
Action2: "InitialState",
Action3: "State1",
DefaultAction: "State2",
},
State3: {
Action1: "InitialState",
Action2: "State1",
Action3: "State2",
DefaultAction: "State3",
},
};
const nextState = (input) => {
const action = actions[input] || actions["DefaultAction"];
const state = transitions[currentState][input] || transitions[currentState]["DefaultAction"];
action();
currentState = state;
};
// initial action
actions["DefaultAction"]();
// iterate over inputs and transition to next state for each input
for (const input in inputs) {
if (inputs.hasOwnProperty(input)) {
nextState(input);
}
}
};
// Example usage
const inputs = { Action1: "", Action2: "", Action3: "" };
stateMachine(inputs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment