Playing Streams with KefirJS

artydev

artydev

Posted on December 19, 2020

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
💖 💪 🙅 🚩
artydev
artydev

Posted on December 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Playing Streams with KefirJS
streams Playing Streams with KefirJS

December 19, 2020