DEV Community

Discussion on: Mastering Hard Parts of JavaScript: Callbacks IV

Collapse
 
sarratas profile image
Sarratas • Edited

Hi,

Your solution for exercise 20 is not really correct. It works for provided functions and inputs, but won't work for situations where, for example, first function appends something to the string. It also assumes that parameters are strings.

Example where it will fail (return ssss):

const addS = (str) => str + 's';
const addLowerCase = (str) => str + str.toLowerCase();
const repeat = (str) => str + str;
const capAddlowRepeat = [addS, addLowerCase, repeat];
console.log(pipe(capAddlowRepeat, "cat"));
Enter fullscreen mode Exit fullscreen mode

I believe more complete and actually also simpler solution is to correctly use initial value of reduce, like below:

function pipe(callbacks, value) {
  return callbacks.reduce((accum, cb) => cb(accum), value);
}
Enter fullscreen mode Exit fullscreen mode

Cheers!