Skip to content
Advertisement

reduce function composed of map function in JavaScript

Say we have

var i = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

and want to reduce() it like

var plus = function(a, b)
{
  return a + b;
};

var s = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  .reduce(plus);

console.log(s);

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!):

var numbers = [1,2,3,4,5];
var map = function(arr, callback) {
  return arr.reduce(function(start, value) {
    start.push(callback(value));
    return start;
  }, []);
};

var newArray = map(numbers, function(value) {
  return value * 3;
});
console.log(newArray); // prints [3,6,9,12,15]

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