Multiple Function Composition

“Function Composition” sounds complicated, what is it?

It’s actually simple to explain and hopefully understand. (Multiple) function composition is the generation of a high-order function by combining simpler functions. It’s probably easier explained using an example.

Basic example using functional.js to combine two functions

1
2
3
4
5
6
7
8
9
var f = function (a) {
return "hello " + a;
};
var g = function (a) {
return a + 1;
};
var composed = λ.compose(f, g);
expect(composed(1)).toEqual("hello 2");

As you can see, the output from the right-most function is passed as the argument to the next function on the left, you’re then returned “hello 2” as a single result. Thanks to @ryansroberts for this one.

Example using functional.js to combine three functions

1
2
3
4
5
6
7
8
9
10
11
12
var e = function (a) {
return "hello " + a;
};
var f = function (a) {
return a + 1;
};
var g = function (a) {
return a * 100;
};
var composed = λ.compose(e, f, g);
expect(composed(2)).toEqual("hello 201");

This example illustrates the combining of multiple functions, passing the output from function “g” as a parameter to function “f”, then passing the output from function “f” as a parameter to function “e”. This leaves you with a single returned result, in this case “hello 201”.

Ah ha! This is just inheritance for JavaScript

Haha, no :) it’s not a function inheriting properties from another function, it’s a function composed of other functions. I suggest you look up prototypal inheritance. Sometimes it’s ok to link to Crockford.

What’s the benefit?

Other than making you look clever, composing functions improves code maintainability and function reuse. I believe that by using high-order functions and point-free programming, it makes your JavaScript much easier to read too. It’s the future, things move on… you’re not still using VB6 are you (can safely assume that if you’re reading this).

functional.js (λ)

It’s coming on, and expect more function-level programming support soon. Don’t be shy to contribute and note that I’m currently using 4 soft spaces for tabs, don’t make me go all Crockford on you.