Skip to content

Instantly share code, notes, and snippets.

@shisama
Created February 2, 2020 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shisama/2eaf1c2e10266149d0b400faa947e4fb to your computer and use it in GitHub Desktop.
Save shisama/2eaf1c2e10266149d0b400faa947e4fb to your computer and use it in GitHub Desktop.
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}`); // current state: off
state = machine.transition(state, 'switch'); // transition action for "switch" in "off" state
console.log(`current state: ${state}`); // current state on
state = machine.transition(state, 'switch'); // transition action for "switch" in "on" state
console.log(`current state: ${state}`); // current state off
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment