Last active
November 4, 2024 17:37
-
-
Save nash403/aeba0b1afe6734a22a9368757a0c325d to your computer and use it in GitHub Desktop.
The simplest state machine in JS. You don't always need bulletproof solutions like XState. Copied from a Kent C. Dodds' article
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
// Copied from this article https://kentcdodds.com/blog/implementing-a-simple-state-machine-library-in-javascript | |
function createMachine(stateMachineDefinition) { | |
const machine = { | |
value: stateMachineDefinition.initialState, | |
transition(currentState, event) { | |
const currentStateDefinition = stateMachineDefinition[currentState] | |
const destinationTransition = currentStateDefinition.transitions[event] | |
if (!destinationTransition) { | |
return | |
} | |
const destinationState = destinationTransition.target | |
const destinationStateDefinition = | |
stateMachineDefinition[destinationState] | |
destinationTransition.action() | |
currentStateDefinition.actions.onExit() | |
destinationStateDefinition.actions.onEnter() | |
machine.value = destinationState | |
return machine.value | |
}, | |
} | |
return machine | |
} | |
const machine = createMachine({ | |
initialState: 'off', | |
off: { | |
actions: { | |
onEnter() { | |
console.log('off: onEnter') | |
}, | |
onExit() { | |
console.log('off: onExit') | |
}, | |
}, | |
transitions: { | |
switch: { | |
target: 'on', | |
action() { | |
console.log('transition action for "switch" in "off" state') | |
}, | |
}, | |
}, | |
}, | |
on: { | |
actions: { | |
onEnter() { | |
console.log('on: onEnter') | |
}, | |
onExit() { | |
console.log('on: onExit') | |
}, | |
}, | |
transitions: { | |
switch: { | |
target: 'off', | |
action() { | |
console.log('transition action for "switch" in "on" state') | |
}, | |
}, | |
}, | |
}, | |
}) | |
let state = machine.value | |
console.log(`current state: ${state}`) | |
state = machine.transition(state, 'switch') | |
console.log(`current state: ${state}`) | |
state = machine.transition(state, 'switch') | |
console.log(`current state: ${state}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment