Function composition using Reduce
1 min read

Function composition using Reduce

Consider we have a bunch of functions.

const double = x => 2 * x;
const triple = x => 3 * x;
const quadruple = x => 4 * x;

Composing these functions feels cryptic and error-prone

quadruple(quadruple(1)); //?
triple(quadruple(quadruple(1))); //? 
add2(triple(quadruple(quadruple(1))));//

From left to right, the last operation reads add2, triple, quadruple, and quadruple, but the calculation happens precisely in reverse, from the inner side to the outer.

Reduce brings clarity and the natural order of function application while reading it.

[quadruple, quadruple].reduce((acc, f) => f(acc), 1 ); //16
[quadruple, quadruple, triple].reduce((acc, f) => f(acc), 1 ); //48
[quadruple, quadruple, triple, add2].reduce((acc, f) => f(acc), 1 );// 50