-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuncSeqPipe.js
More file actions
26 lines (22 loc) · 837 Bytes
/
funcSeqPipe.js
File metadata and controls
26 lines (22 loc) · 837 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* The pipe function takes a sequence of functions and
* returns a new function. When the new function is called
* with an argument, the sequence of functions are called in order,
* which each one receiving the return value of the previous function.*/
const pipe =
(...functions) =>
(initialValue) =>
functions.reduce((acc, fn) => fn(acc), initialValue);
// Building blocks to use for composition
const double = (x) => 2 * x;
const triple = (x) => 3 * x;
const quadruple = (x) => 4 * x;
// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);
// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240