Arrows in JavaScript

November 22, 2014

Arrows are a neat way to chain functions together in interesting ways.

In JavaScript, an arrow might look like this:

function arrow(f) {
  function compose(g) {
    return arrow(
      function(x) {
        return g(f(x));
      }
    );
  }
  function first(g) {
    return arrow(
      function (x) {
        var ys = f(x);
        return [g(ys[0]), ys[1]];
      }
    );
  }
  function second(g) {
    return arrow(
      function (x) {
        var ys = f(x);
        return [ys[0], g(ys[1])];
      }
    );
  }
  function merge(g) {
    return arrow(
      function(x) {
        return [f(x[0]), g(x[1])];
      }
    );
  }
  function split(g) {
    return arrow(
      function(x) {
        return [f(x), g(x)];
      }
    );
  }
  return {
      arr: f
    , compose: compose
    , first: first
    , second: second
    , merge: merge
    , split: split
  };
}

Demo

Let's use arrows to string together the following functions:

function id(x)    { return x; }
function x2(x)    { return x * 2; }
function x3(x)    { return x * 3; }
function dec(x)   { return x - 1; }
function mult(xs) { return xs[0] * xs[1]; }

We'll build up a workflow to calculate 42:

      .--> id --> x2 --> x3 -----------------.
     /      1      2      6                   \
1 --:                                           mult --> 42
     \                                        /  42
      '--> id --> x2 --> x2 --> x2 --> dec --'
            1      2      4      8      7
var p = arrow(id).split(id)
          .first(x2).first(x3)
          .second(x2).second(x2).second(x2).second(dec)
          .compose(mult);