Last active
May 8, 2021 21:14
-
-
Save tnguven/ad474ebe81faee2b83150ab19ce811c8 to your computer and use it in GitHub Desktop.
State machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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