DEV Community

artydev
artydev

Posted on • Updated on

Challenge : write the most tiny counter using your favorite library

Requirements :

  • the counter implementation and it's usage must be on the same page
  • the view consist of a single value and two buttons : inc and dec

Here is mine using DML library:

import {button, idiv} from "./dml"; /* <sdtio.h> :-) */

function Counter () {
    let count = 0;
    let value = idiv("0");
    let binc = button("inc");
    let bdec = button("dec");
    binc.onclick = () => value.innerText = ++count;
    bdec.onclick = () => value.innerText = --count;
}

Counter();
Enter fullscreen mode Exit fullscreen mode

You can test it here : TinyCounter

Show yours :-)

Here is a better implementation from Eckehard, thanks to him :

import {button, idiv} from "./dml"; /* <sdtio.h> :-) */

function Counter () {
    let value = idiv("0");
    button("inc").onclick = () =>value.innerText = Number(value.innerText)+1
    bdec = button("dec").onclick = () => value.innerText = Number(value.innerText)-1
}

Counter();
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
efpage profile image
Eckehard

As you may know, it is not necessary to create variables for the buttons in this case. And removing the counter may not be very elegant, but removes the double storage of a value. It is generally advised to use the state of a DOM element directly to avoid misalignments:

import {button, idiv} from "./dml"; /* <sdtio.h> :-) */

function Counter () {
    let value = idiv("0");
    button("inc").onclick = () =>value.innerText = Number(value.innerText)+1
    bdec = button("dec").onclick = () => value.innerText = Number(value.innerText)-1
}

Counter();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
artydev profile image
artydev

Thank you very much Eckehard.
I appreciate your advises, don't hesitate :-)
Regards