DEV Community

Cover image for Create a very simple State Machine with closures
artydev
artydev

Posted on • Updated on

Create a very simple State Machine with closures

State machine are a great way to render consistent view.
Here is a very simple example of a state machine created via a closure.

Once the state machine created, you simply pass it the desired transition, and the state machine returns the updated one.

You can test it here SimpleStateMachineDemo

const {m, dom, udom, render, html } = MVU;

const h1 = m("h1");
const button = m("button");

function evaluate_state_machine (state, transition) {
  switch(transition) {
      case("inc") :
        state = {...state, counter : state.counter += 1 }
        break;
      case("dec") :
        state = {...state, counter : state.counter -= 1 }
        break;    
      default:
        state = state
  }
  return state;
}

function state_machine () {
  let state =  {
    counter : 0
  }
  function _state_machine (transition) {
    state = evaluate_state_machine(state, transition);
    return state;
  }
  return  _state_machine;
}

function App (sm) {
  let state = sm();
  let app = dom ();
    h1(`State machine demo : ${state.counter}`)
    button("inc").onclick = () => { sm("inc"); update_app (sm)};
    button("dec").onclick = () => { sm("dec"); update_app (sm)};
  udom ();
  return app;
}
let sm = state_machine();

function update_app (sm) {
  render(app, App(sm));
}

update_app (sm);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)