File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments