«

»

Mar 03

Flapjax – Functional Reactive Programming in Javascript

What if programming can be as simple as writing spreadsheet formulas?

Now – there are some complex spreadsheets out there for sure, but the power of spreadsheet comes from that the values are self-updating, i.e. changing value in one cell will automatically cause all its dependent cells to reflect the change.  If spreadsheets cannot do the auto-propagation, even the simplest spredsheet will be much more complex.

Most programming languages do not have the auto-propagating capability, but the ones that do are called reactive programming languages.  And if the language is also functional, then it’s called a functional reactive programming language.

Since most of the mainstream languages did not have reactive features built-in, the feature need to be “bolted on”, as a library or a transformer.  The one for Javascript is called Flapjax.

Let’s do a quick example to demonstrate the power of functional reactive programming.  We’ll use timer as an example, where the timer should refresh its value (in total milliseconds) every tenth of a second.

If we were to write this in conventional Javascript, it will be something like this:

var d = new Date();
setTimeout(function () { node.innerHTML = d.getMilliseconds(); } , 100);

But if Flapjax it’s as follows (you can see the demo here):

 {! timerB(100); !}

Cool huh?  The timerB “function” automatically handles the refresh that we have to manually handle with setTimeout in conventional Javascript.

What if we want to have two timers, the first gets updated every tenth of a second, and the second gets updated whenever the first is updated ten times?

In conventional Javascript we will write:

var d = new Date();
var i = 0;
setTimeout(function () { node.innerHTML = d.getMilliseconds();
   i++;
   if (i == 10) {
      node2.innerHTML = Math.floor(d.getMilliseconds());
   } else {
      i = 0;
   }
} , 100);

In Flapjax we can write (see a more extensive demo that includes the last digit of the timer):

var tenthB = timerB(100);
var secondB = Math.floor(tenthB / 1000);
{! tenthB !} {! secondB !}

It now looks like we have created two variables, and as the value of the first variable changes, the second variable changes along with it.  In comparison, the conventional event-driven approach of Javascript has too much code, and also obscures the relationship between the two timers.

This is only the tip of the iceberg of what functional reactive programming can do – for more details, see the Flapjax tutorial.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create