DEV Community

artydev
artydev

Posted on

3

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

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or a friendly comment!

Okay.