Untangling your Logic using State Machines
You may find this article useful if:
You can read JS / Object oriented languages (Python, C++, C#, Java, etc)
You are familiar with writing functions (https://stackoverflow.com/a/4709224)
Introduction
A few weeks ago, I was working on an applicatio...
blog.robruizr.dev6 min read
Great work ! It's always interesting to try implementing a pattern from scratch before switching to a fully fledged library like Xstate.
It got me thinking, I think you could take it one step further, while still avoiding any third-party dependency. Right now your
changeStatedoesn't guarantee that you machine will be executed as described by your diagram.For example nothing prevents you from calling
changeState('fadeOut')from the stateinvisiblewhich shouldn't be possible.This could be solved by implementing the transition function from the mathematical defintion
Something like that :
First you'd add the transition to your state defintion
const buttonStates = { // You could also map these to a number instead of the same string, // but this is personal preference as it's easier to debug. fadingOut: { show: "visible", hide: "invisible" }, visible: { reset: "visible", fade: "fadingOut" }, invisible: "{ show: "visible" } };Then the transition function could be defined like so:
const transition = (state, event) => { return buttonStates[state][event] }Which would allow you to call
transition(button.state, "fade")Might be overkill for your use case, but thought it was worth mentioning :)