Skip to content

Commit 7acdb08

Browse files
committed
Implement pipe function with reduce
1 parent f3a075d commit 7acdb08

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

javascript/reduce.js

+20
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ const arr = [1, 2, 3, 4, 5];
55
// Building a sum function with reduce
66
const sumReducer = (acc, value) => acc + value;
77

8+
log('Sum with Reduce');
89
let total = arr.reduce(sumReducer, 0);
910
log(total); // 15
11+
log();
1012

1113
/* -------------------------------------- */
1214

@@ -53,6 +55,7 @@ let evenValues = filter(isEven, arr);
5355
log('Filter with Reduce');
5456
log(moreThan3Value); // [4, 5]
5557
log(evenValues); // [2, 4]
58+
log();
5659

5760
/* -------------------------------------- */
5861

@@ -71,4 +74,21 @@ const h = (x) => x * 3;
7174
const composedFns = compose(f, g, h);
7275
let finalValue = composedFns(2);
7376

77+
log('Compose with Reduce');
7478
log(finalValue); // 4
79+
log();
80+
81+
/* -------------------------------------- */
82+
83+
// Building a pipe function with reduce
84+
// API: pipe(fn1, fn2, fn3, ...)
85+
// fn1: function to be composed
86+
87+
const pipe = (...fns) => x => fns.reduce((pipedFns, fn) => fn(pipedFns), x);
88+
89+
const pipedFns = pipe(f, g, h);
90+
finalValue = pipedFns(1);
91+
92+
log('Pipe with Reduce');
93+
log(finalValue); // 3
94+
log();

0 commit comments

Comments
 (0)