Mar
Mar

Reputation: 125

Recreating JavaScript Reduce function part 2

This in relation to the reduce function I recreated here, but a different question: Recreating JavaScript's reduce function.

I am reading Eloquent JavaScript and noticed that they recreated the reduce function a slightly different way with less code:

function reduce(array, combine, start) {
  var current = start;
  for (var i = 0; i < array.length; i++)
    current = combine(current, array[i]);
  return current;
}

console.log(reduce([1, 2, 3, 4], function(a, b) {
  return a + b;
}, 0)); // → 10

I noticed that this only works when there is a start. For example, if I took away the start(0) and it was just:

console.log(reduce([1, 2, 3, 4], function(a, b) {
  return a + b;
})); // NaN

It would return NaN. This doesn't make sense to me because the book says: "If your array contains at least one element, you are allowed to leave off the start argument. The method will take the first element of the array as its start value and start reducing at the second element."

Only when I adjust it with an if statement does it produce "10" with or without a start(0).

function reduce(array, combine, start) {
  var current = start;

  for (var i = 0; i < array.length; i++)
    if(current !==undefined){
      current = combine(current, array[i]);
    }else{
      current=array[i]; 
    }

 return current;
}

What am I missing?

Upvotes: 1

Views: 380

Answers (1)

Louay Alakkad
Louay Alakkad

Reputation: 7408

Here's how it should be, according to MDN (simplified version here):

function reduce(array, combine, start) {
  var current = start;
  var i = 0;
  if (arguments.length < 2) {
    while (array[i] === undefined) {
      i ++;
      if (array.length >= i) {
        throw new Error('Empty array with no initial value');
      }
    }
    current = array[i];
  }

  for (; i < array.length; ++ i) {
    if (array[i] === undefined) continue;
    if (current !== undefined) {
      current = combine(current, array[i]);
    } else {
      current=array[i]; 
    }
  }

  return current;
}

Upvotes: 2

Related Questions