DEV Community


Posted on

Playing Streams with KefirJS

Kefir is a lighter alernative to RxJS.

Here is a simple counter in functional reactive programming.

You can play with it here kefirCounter

  src="" >

<button id="inc">+</button>
<span id="result">0</span>
<button id="dec">-</button>

  /****************** Helpers **********************/
  const elt = (id) => document.getElementById(id);
  const fromEvts = Kefir.fromEvents;
  const merge = Kefir.merge;
  const clickEvt = "click";
  const ident = (v) => () => v;
  const one = ident(1);
  const negone = ident(-1);
  const add = (x, y) => x + y;

  const inc$ = 
    fromEvts(elt("inc"), clickEvt)

  const dec$ = 
    fromEvts(elt("dec"), clickEvt)

  const sum$ = 
    merge([inc$, dec$])
      .scan(add, 0)
      .onValue(s => result.innerText = s);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)