Skip to content
Advertisement

reduce function composed of map function in JavaScript

Say we have

JavaScript

and want to reduce() it like

JavaScript

Now, I want to compose reduce() function itself from map() function.

How would you do that? What is the smartest way?

Edit:

In the comments and answers, many have claimed fold/reduce can compose map, in shallow level, that can be true, however, in category theory, fundamentally reduce/fold is generalized to Catamorphism and it’s all about functors (map), and it’s called F-algebra.

https://en.wikipedia.org/wiki/Catamorphism

https://en.wikipedia.org/wiki/F-algebra

Advertisement

Answer

If you’re trying to build the map function using reduce, you could do the following (The example I’m providing will use built-in functions and work for arrays only!):

JavaScript

This will iterate through each of the values in our numbers array, invoke (execute) the callback function using the current value we’re looping over, and then push this value to an empty array which will be returned at the end of reduce. In other words, it will map the results of our callback function to a new array!

That being said, if you’re interested in functional programming, I would encourage you to check out underscorejs’s annotated source code.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement