10 More Utility Functions Made with Reduce

This time, with a test suite!

Yazeed Bzadough
Frontend Weekly

--

Previously I wrote about 10 utility functions implemented with JavaScript’s reduce function. It was well-received, and I walked away with an even deeper appreciation for this magnificent multi-tool. Why not try 10 more?

Many of these were inspired by the awesome libraries Lodash and Ramda! I also wrote unit tests to ensure correct behavior. You can see everything on the Github repo here.

1. pipe

Parameters

  1. ...functions - Any number of functions.

Description

Performs left-to-right function composition. The first argument to a pipeline acts as the initial value, and is transformed as it passes through each function.

Implementation

const pipe = (...functions) => (initialValue) =>
functions.reduce((value, fn) => fn(value), initialValue);

Usage

const mathSequence = pipe(
(x) => x * 2,
(x) => x - 1,
(x) => x * 3
);

mathSequence(1); // 3
mathSequence(2); // 9
mathSequence(3); // 15

For more detail, I wrote an article on pipe here.

--

--