Recreating JavaScript's reduce function

2019-08-21 02:52发布

I'm trying to recreate the reduce method but as the original function.

This helped me to understand a lot but I have one little issue: How to re-create Underscore.js _.reduce method? When I plug in arrays it works right, but objects don't work. I get undefined. I would appreciate advice on what I should change. I commented where I think I should change something but I'm confused exactly what I need to change it to. I also created my own each function.

You can find my code here: http://goo.gl/6RU9Bc

Any advice would be super helpful. Thank you!!

This is what I have so far:

var myArray=[1,2,3,4,5];

var myObject={
  num1:1,
  num2:2,
  num3:3
};

function each(collection, callback){
  if(Array.isArray(collection)) {
    for(var i=0, l=collection.length; i<l; i++){
      callback(collection[i]); 
    };
  }else if(collection === "object") {
    for(var prop in collection){
       callback(collection[prop]);
    };
  }
}

function multiply(num, num2){
  return num*num2;
}

function reduce(collection, callback, accumulator){
  each(collection, function(element){
    if(accumulator === undefined) {
      return accumulator = element; // is the problem here? Why? I don't understand.
    }else {
      return accumulator = callback(accumulator, element);
    };   
});

return accumulator;
};

console.log(reduce(myArray, multiply)); // 120
console.log(reduce(myArray, multiply, 5)); // 160
console.log(reduce(myObject, multiply)); // returns undefined
console.log(reduce(myObject, multiply, 5)); // returns 5

1条回答
放荡不羁爱自由
2楼-- · 2019-08-21 03:32

As pointed out by @Yeldar Kurmangaliyev, you need to change this:

if(collection === "object")

to:

if(typeof(collection) === "object")

Here is the fixed code:

var myArray=[1,2,3,4,5];

var myObject={
  num1:1,
  num2:2,
  num3:3
};

function each(collection, callback){
  if(Array.isArray(collection)) {
    for(var i=0, l=collection.length; i<l; i++){
      callback(collection[i]); 
    };
  }else if(typeof(collection) === "object") {
    for(var prop in collection){
       callback(collection[prop]);
    };
  }
}

function multiply(num, num2){
  return num*num2;
}

function reduce(collection, callback, accumulator){
  each(collection, function(element){
    if(accumulator === undefined) {
      return accumulator = element; // is the problem here? Why? I don't understand.
    }else {
      return accumulator = callback(accumulator, element);
    };   
});

return accumulator;
};

console.log(reduce(myArray, multiply)); // 120
console.log(reduce(myArray, multiply, 5)); // 600
console.log(reduce(myObject, multiply)); // 6
console.log(reduce(myObject, multiply, 5)); // 30
查看更多
登录 后发表回答