Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write my own `reduce` function?

Tags:

javascript

I want write reduce by myself. But over the last 4 hours, I couldn't.

var a = [10, 21, 13, 56];

function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }

Array.prototype.reduce2 = function () {
  // I do not understand how to handle the function of the inlet
  // I know that I should use arguments, but I don't know how many arguments there will be
  var result = 0;
  for(var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
 return result;
};

console.log(a.reduce(add), a.reduce2(add))         // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110

Yes, I know that this seems like a lot of topics, but I couldn't find answer. What am I missing, or doing wrong here?

like image 705
SergeyB Avatar asked Oct 31 '16 20:10

SergeyB


1 Answers

The array in subject is not passed as argument, but is the context (this).

You also need to distinguish between the presence or absence of the start value:

var a = [10, 21, 13, 56];

function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }

Array.prototype.reduce2 = function (f, result) {
  var i = 0;
  if (arguments.length < 2) {
    i = 1;
    result = this[0];
  }
  for(; i < this.length; i++) {
    result = f(result, this[i], i, this);
  }
  return result;
};
console.log(a.reduce(add), a.reduce2(add))         // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110
// extra test with foo:
console.log(a.reduce(foo, 'X'), a.reduce2(foo, 'X')) // X10211356 X10211356
like image 60
trincot Avatar answered Oct 21 '22 15:10

trincot