Skip to content

Commit be7c301

Browse files
committed
Create Function Sequence Piping js file
- MDN example to play with demonstrating using Array.prototype.reduce on a sequence of functions
1 parent 79330b3 commit be7c301

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

funcSeqPipe.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/* The pipe function takes a sequence of functions and
2+
* returns a new function. When the new function is called
3+
* with an argument, the sequence of functions are called in order,
4+
* which each one receiving the return value of the previous function.*/
5+
6+
const pipe =
7+
(...functions) =>
8+
(initialValue) =>
9+
functions.reduce((acc, fn) => fn(acc), initialValue);
10+
11+
// Building blocks to use for composition
12+
const double = (x) => 2 * x;
13+
const triple = (x) => 3 * x;
14+
const quadruple = (x) => 4 * x;
15+
16+
// Composed functions for multiplication of specific values
17+
const multiply6 = pipe(double, triple);
18+
const multiply9 = pipe(triple, triple);
19+
const multiply16 = pipe(quadruple, quadruple);
20+
const multiply24 = pipe(double, triple, quadruple);
21+
22+
// Usage
23+
multiply6(6); // 36
24+
multiply9(9); // 81
25+
multiply16(16); // 256
26+
multiply24(10); // 240

0 commit comments

Comments
 (0)