DEV Community

Discussion on: Can you solve this JavaScript problem?

Collapse
sadarshannaiynar profile image
Adarsh • Edited on

You can also do by this by leveraging Array.prototype.reduce.

const addOne = num => num + 1;
const subtractTwo = num => num - 2;
const multiplyThree = num => num * 3;

const compose = (...fns) => val => fns.reduce((acc, fn) => fn(acc), val);

const resp = compose(addOne, subtractTwo, multiplyThree);

console.log(resp(4)); // 9
Collapse
varundey profile image
Varun Dey Author

We definitely can. But as I said, I always get confused with the argument order of reduce and since I didn't want to Google my way through this one, I went with forEach

Collapse
sadarshannaiynar profile image
Adarsh

I used to struggle as well but with practice you will get the hang of it. Once you start using array methods you can get lot of things with as little code as possible.