Freeing JavaScript from JavaScript.

— An evil strategy to make JavaScript more functional

As of ES6, we’re used to Array methods such as map, filter, and reduce. Methods borrowed from functional programming languages.

I’ve got no issues with those methods. But if we want to write JavaScript in an even more functional style we should adapt them a bit. Since they’re not curried, we can’t make use of a partial application. Luckily this is easily fixed:

const map = (fn) => (xs) => xs.map(fn);

However, this means we always have to supply the last last, as a separate function invocation,

inc = (x) => x + 1;> map(inc)([1,2,3]);
[ 2, 3, 4 ]

Therefore we’d most likely rather make this as an option in the implementation.

const map = (fn, xs) => !xs ? (xs) => xs.map(fn) : xs.map(fn);

Now we can write:

> map(inc, [1, 2, 3])
[ 2, 3, 4 ]

But also,

> map(inc)([1, 2, 3])
[ 2, 3, 4 ]

This is all good. We could free quite a few ES6 Array methods similarly. To me, the main advantage though arises when we use our more functional style function in a pipe or a compose, functional programing functions used to make compositions for function and data.

> const compose = (…fns) => (initial) => fns.reduceRight((a, b) => b(a), initial);
> compose( map(inc), map(inc))([1,2,3]);
[ 3, 4, 5 ]

A major difference is that this structure frees us from the data type. We can use compose on whatever data type, while the chained Array methods only handle lists.
 This means we could write,

> compose (inc, inc, inc)(0);
3

Also, if we free new ES6 functional programming methods from the Array prototype, we still have them available. We make it a matter of taste, a choice that’s quite nice to always have available. Partial application is a useful concept.

Leave a Reply