Function composition is a programming technique that could be very useful and very expressive at the same time.
Essentially it consists to combine N simple (unary and hopefully pure) functions making the output of a function being the input for another one.
To make working function composition in Javascript we need to extend the Function object with a polyfill (inspired by this great book):
Function.prototype.compose = function(firstFunc) { var secondFunc = this; return function() { return secondFunc.call(this, firstFunc.apply(this, arguments)); } }
How does it work?
Every function composed get as input the output of the latter one applied.
A pratical example:
function first(string) { return string + "the quick brown fox"; } function second(string) { return string + " jumps over "; } function third(string) { return string + "the lazy dog"; } var composeString = first.compose(second).compose(third); console.log(composeString('English course lesson 1: '));
That one produces:
“English course lesson 1: the lazy dog jumps over the quick brown fox”
Why?
Because the compose polyfill works from right to the left. The last function on the right will be the first applied.
Here is the the more natural (for western people, at least) version of compose: the sequence polyfill, from left to right:
Function.prototype.sequence = function(firstFunc) { var secondFunc = this; return function() { return firstFunc.call(this, secondFunc.apply(this, arguments)); } } var sequenceString = first.sequence(second).sequence(third); console.log(sequenceString('English course lesson 1: '));
That one produces:
“English course lesson 1: the quick brown jumps over fox the lazy dog”
Besides the order of function application, I think the interesting thing of this approach, and the functional programming in general, is to produce efficient and readable code based on the smallest possible chunks, Unix style.
That improves decoupling and bug fixing.
And… regarding readability, just one word: Elixir!
In Elixir is not needed a polyfill because the function composition is built-in in the language, via the wonderful Elixir Pipe operator: “|>”
Lets’ define a module that contains our functions.
defmodule Sequence do def first(s), do: "#{s} the quick brown fox" def second(s), do: "#{s} jumps over" def third(s), do: "#{s} the lazy dog" end
then save it into “sequence.exs” and load it into iex:
$ iex sequence.exs
and try it:
iex> "English course lesson 1: " |> Sequence.first |> Sequence.second |> Sequence.third |> IO.Puts
that produces
“English course lesson 1: the quick brown fox jumps over the lazy dog”
This is a very trivial example that shows the readability and the expressiveness of the Elixir programming language.