DEV Community

Discussion on: Demystifying Array.reduce(): How to understand it and when to use it in your code

Collapse
 
dance2die profile image
Sung M. Kim • Edited

My favorite is a pipe method.

const pipeOnce = (fn1, fn2) => (args) => (fn2(fn1(args)));
const pipe = (...ops) => ops.reduce(pipeOnce);
// OR const pipe = (...ops) 
//     => ops.reduce((fn1, fn2) => (args) => (fn2(fn1(args))));

const addTwo = a => a + 2;
const mulTwo = a => a * 2;

const addTwoMulTwo = pipe(addTwo, mulTwo);
console.log(addTwoMulTwo(1));  // (1 + 2) * 2 => 6
console.log(addTwoMulTwo(2));  // (2 + 2) * 2 => 8
console.log(addTwoMulTwo(3));  // (3 + 2) * 2 => 10

It's just amazing that you can not only pass an array of objects, you can pass an array of functions, as a function is a first-class citizen in JavaScript.

And also, C# has a reduce method named Aggregate, which I think reflects more of what it does.