DEV Community

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

Posted on • Edited on

2

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay