Skip to content

Instantly share code, notes, and snippets.

@tnguven
Last active May 8, 2021 21:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tnguven/ad474ebe81faee2b83150ab19ce811c8 to your computer and use it in GitHub Desktop.
Save tnguven/ad474ebe81faee2b83150ab19ce811c8 to your computer and use it in GitHub Desktop.
State machine
const machine = {
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: 'active',
}
},
active: {
on: {
TOGGLE: 'inactive'
}
}
}
}
function transition(state, event) {
return machine.states[state]?.on?.[event] || state;
}
function toggleState(initialState) {
let currentState = initialState;
return (event) => {
currentState = transition(currentState, event);
console.log({ currentState });
}
}
const send = toggleState('inactive');
send('TOGGLE');
send('TOGGLE');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment