Created
February 2, 2020 03:34
-
-
Save shisama/2eaf1c2e10266149d0b400faa947e4fb to your computer and use it in GitHub Desktop.
state machine implement referred to https://kentcdodds.com/blog/implementing-a-simple-state-machine-library-in-javascript
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
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