DEV Community

Cover image for Javascript State Machine
artydev
artydev

Posted on

Javascript State Machine

State Machines are awesome tools, every developpers should know them.

JavascriptStateMachine have a nice implementation and is simple to use.

Here is an exemple Melting

The machine definition

import javascriptStateMachine from 'https://cdn.skypack.dev/javascript-state-machine';

const StateMachine = javascriptStateMachine;

function Machine (updateView) {
  var fsm = new StateMachine({
  init: 'solid',
  transitions: [
      { name: 'melt',     from: 'solid',  to: 'liquid' },
      { name: 'freeze',   from: 'liquid', to: 'solid'  },
      { name: 'vaporize', from: 'liquid', to: 'gas'    },
      { name: 'condense', from: 'gas',    to: 'liquid' }
    ],
    methods : {
      onAfterTransition : (fsm) =>  {
        (fsm.transition != "init") && updateView() 
      }
    }
  });
 return fsm;
}


export { Machine }
Enter fullscreen mode Exit fullscreen mode

It's use :

import {
    Machine
} from "./machine.js"

window.app = (function Application() {

    const buttons = Array.from(document.querySelectorAll("button"));

    function disableButton(elt) {
      elt.disabled = true
    }

    function resetButtons () {
        buttons.forEach(disableButton);
    }

    function initFSM() {
        return Machine(updateView);
    }

    const fsm = initFSM();

    function View () {
        buttons.forEach(b => { 
          if (fsm.transitions().includes(b.dataset.transition))   
            b.disabled = false 
          })
    }

    function updateView() {
      resetButtons()
      View()
    }

    updateView();

    return {
        fsm
    }

})();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)