DEV Community

artydev
artydev

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

<script 
  src="https://cdnjs.cloudflare.com/ajax/libs/kefir/3.8.0/kefir.min.js" >
</script>

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

<script>
  /****************** 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)
      .map(one);

  const dec$ = 
    fromEvts(elt("dec"), clickEvt)
      .map(negone);

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

</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)