learnrx icon indicating copy to clipboard operation
learnrx copied to clipboard

A better way (i guess) to implement reduce

Open svallory opened this issue 11 years ago • 3 comments

Hi, I was following the tutorial and noticed that on exercise 16, where reduce is implemented using a while and a counter, effectively determining how the array should be traversed. Check the code below

while(counter < this.length) {
  accumulatedValue = combiner(accumulatedValue, this[counter])
  counter++;
}

I just started studying RX but, as far as I get it, one of the key points is to leave to the underlying libraries decide how to traverse the arrays? If so, I think the reduce could be better implemented like this:

var accumulatedValue;

if (arguments.length === 1) {
  counter = 1;
  // DON'T SET IT TO ANY ELEMENT
  // accumulatedValue = this[0]; 
}
else if (arguments.length >= 2) {
  counter = 0;
  accumulatedValue = initialValue;
}
else {
  throw "Invalid arguments.";
}

this.forEach(function(it) {
  if(typeof accumulatedValue == 'undefined') {
    accumulatedValue = it;
  }
  else {
    accumulatedValue = combiner(accumulatedValue, it)
  }
})

svallory avatar Aug 22 '14 05:08 svallory

I think what you're going for is something like this?

Array.prototype.reduce2 = function(combiner, initialValue) {
    var accumulatedValue = initialValue;

    if (this.length === 0) {
        return this;
    }

    if (arguments.length === 0) {
        throw "Invalid arguments.";
    }

    this.forEach(function(it) {
        if (!accumulatedValue) {
            accumulatedValue = it;
        } else {
            accumulatedValue = combiner(accumulatedValue, it);
        }
    });

    return [accumulatedValue];
};

The only problem I see is that you're performing an extra if for each item in the array, which isn't a big deal, but it is unnecessary overhead. I imagine that's why they opted for while.


One thing I find odd is that their implementation of .reduce() always returns an array, which is different than the native ES5 version. I'm not sure if this was on purpose.

[1,2,3,4,5].reduce(function(a, b) {
    return a + b;
});
// ES5     =>  15
// learnRX => [15]

echenley avatar Dec 13 '14 21:12 echenley

I am curious as well as to why the an array is always returned, that was really throwing me for a loop in the examples as I was used to the ES5 way. Does anyone know if that was a mistake or there was some rationale to it?

wavded avatar Dec 18 '14 06:12 wavded

:+1:

despairblue avatar Apr 22 '15 22:04 despairblue