简体   繁体   中英

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

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 .

map returns one value for every value in the array, thus the result will be an array just as big as the input array. The only way to get one value out of it is by sending only one value into it.

[[1,2,3,4,54]].map(
    function(d){
        sum = d.reduce(function(s,d){
                     return s+d
                 });
        console.log(sum)
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM