Composing functions

Hi there,

Earlier in the post about classes vs composition i mention some of the same ideas briefly.

The basic idea with a compose or a pipe function is, that it takes an arbitrary number of functions and passes the return values from one to the next. compose does it from rigth to left and pipe does it from left to rigth.

First example without composing is:

const function1 = input => `${input} m^2`
const function2 = input => `I would like a house that is more than ${input} big`

console.log(function2(function1(2))) // I would like a house that is more than 2 m^2 big

Already with one function passed into the other it looks a bit silly. If you image having more input functions, it quickly becomes very unreadable.

The same exmpla with a compose function:

const function1 = input => `${input} m^2`
const function2 = input => `I would like a house that is more than ${input} big`

const compose = (...fns) =>
    fns.reverse().reduce((prevFn, nextFn) =>
        value => nextFn(prevFn(value)),
        value => value
    );
const example = compose(
    function2,
    function1
);    
console.log(example(2)); // I would like a house that is more than 2 m^2 big

Now that was a lot more code, to do the same thing, but.
If you already have the compose function you can start building easy to read function flows, that passes output from function as input to the next function.

Finally.. Lodash also has a version of compose that can make the whole thing a lot more smooth:

import * as _ from 'lodash'

const function1 = input => `${input} m^2`
const function2 = input => `I would like a house that is more than ${input} big`

const lodashWay = _.flowRight(function2, function1);


console.log(lodashWay(2)) // I would like a house that is more than 2 m^2 big

With libaries like ramda, you can do super cool function compositions, that uses functional programming when its best:

const R = require('ramda');

let diffFromNow = date => new Date(date) - new Date();
let fromMiliTominutes = milli => R.divide(milli, (1000 * 60));
let dateMoreThan1HourAgo = R.compose(
    R.gte(R.__, 60),
    Math.round,
    fromMiliTominutes,
    diffFromNow);

let date = new Date();
let diff = dateMoreThan1HourAgo(date.setHours(date.getHours() + 1));
console.log(diff); // true

In the exmaple above i use some of the build in functions in Ramda, like compose (same af lodash flowright())