Simple moving average with bacon.js

Bacon is a small functional reactive programming lib for JavaScript. Sometimes it is easier to handle data as a stream and react to changes in the stream instead of processing individual events. In the example below (nodejs), a simple moving average.

var Bacon = require('baconjs')

function avg(array) {
  var sum = array.reduce(function(a, b) { return a + b; }, 0);
  return sum / array.length;

var bus = new Bacon.Bus();
bus.push(1); // output = 1
bus.push(2); // output = 1.5
bus.push(3); // output = 2

You can see another example (github) where an event stream is created and populated with your mouse positions. The “y” position is represented along with the moving average.

Hello. Call me Guido · Twitter · My bot (alpha) ·