Skip to content

Instantly share code, notes, and snippets.

@michaelmr
Created May 24, 2019 03:11
Show Gist options
  • Select an option

  • Save michaelmr/76505876df9567b7c70da76506f99a31 to your computer and use it in GitHub Desktop.

Select an option

Save michaelmr/76505876df9567b7c70da76506f99a31 to your computer and use it in GitHub Desktop.

Revisions

  1. michaelmr created this gist May 24, 2019.
    38 changes: 38 additions & 0 deletions tinyelm.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    const tinyelm = (init, update, output, debug = console.log) => {
    let state = init;

    output(state);

    return (event) => {
    debug("dispatching event " + JSON.stringify(event));
    debug("cur state " + JSON.stringify(state));
    state = update(event, state);
    debug("output state " + JSON.stringify(state));
    output(state);
    }
    };
    const output = (state) => {
    document.getElementById("count").innerHTML = state.state;
    };
    const update = (event, {state= 0}) => {
    switch (event.type) {
    case "INCREMENT":
    return {state: state + 1};
    case "DECREMENT":
    return {state: state - 1};
    default:
    return {state:state};
    }
    }

    let dispatch= tinyelm({"state":0}, update, output);
    let btnPlus = document.getElementById("inc");
    let btnMinus = document.getElementById("dec");

    btnPlus.addEventListener("click", () => {
    dispatch({ type: "INCREMENT" });
    });

    btnMinus.addEventListener("click", () => {
    dispatch({ type: "DECREMENT" });
    });