DailyJS

most.js: Monadic Reactive Streams

Alex R. Young

Subscribe

@dailyjs

Facebook

Google+

libraries functional modules reactive

most.js: Monadic Reactive Streams

Posted by Alex R. Young on .
Featured

libraries functional modules reactive

most.js: Monadic Reactive Streams

Posted by Alex R. Young on .

Nick Ts. sent in most.js (GitHub: cujojs/most, License: MIT, npm: most), a reactive programming library designed for working with streams of values and events. You can use it with WebSocket, DOM events, and it should work with fantasy land and Promises/A+.

Let's say you've got an HTML fragment that you want to make dynamic. It should update in real-time based on user input. Here's a snippet:

<form>  
  <input class="x"> + <input class="y"> = <span class="result"></span>
</form>  

The goal is to make the form sum two numbers. Given a simple add function, and a function to cast the form's strings to numbers, a reactive most.js implementation could look like this:

var most = require('most');

var xInput = document.querySelector('input.x');  
var yInput = document.querySelector('input.y');  
var resultNode = document.querySelector('.result');

exports.main = function() {  
  // x represents the current value of xInput
  var x = most.fromEvent('input', xInput).map(toNumber);

  // y represents the current value of yInput
  var y = most.fromEvent('input', yInput).map(toNumber);

  // result is the live current value of adding x and y
  var result = most.combine(add, x, y);

  // Observe the result value by rendering it to the resultNode
  result.observe(renderResult);
};

function add(x, y) {  
  return x + y;
}

function toNumber(e) {  
  return Number(e.target.value);
}

function renderResult(result) {  
  resultNode.textContent = result;
}

The API is different to React and Knockout, but you should be able to follow it. There's a method called fromEvent that can map DOM events to JavaScript functions, then a method called combine that creates a new stream based on the streams from the two inputs. What's cool about this is you could further process the streams with to do things like throttling or tailing the results.

The people behind most.js have made sure it performs well, and there are some promising benchmarks. The library itself is from cujoJS, which is described as a toolkit for building web applications. The most.js readme has some functional and ES6 generators, so if you're interested in seeing what most.js looks like with generators then take a look there.

You can use most.js without worrying too much about what things like monads and functors are, but if you're interested in functional programming in JavaScript then you should try out Fantasy Land Specification.