Julio Marins Julio Marins - 5 months ago 124
Javascript Question

How to break on reduce method

How can I break the iteration on reduce method?

for

for (var i = Things.length - 1; i >= 0; i--) {
if(Things[i] <= 0){
break;
}
};


reduce

Things.reduce(function(memo, current){
if(current <= 0){
//break ???
//return; <-- this will return undefined to memo, which is not what I want
}
}, 0)

Answer

You can write your own version of reduce which uses a special token to identify when the loop should be broken.

var EXIT_REDUCE = {};

function reduce(a, f, result) {
  for (let i = 0; i < a.length; i++) {
    let val = f(result, a[i], i, a);
    if (val === EXIT_REDUCE) return result;
    result = val;
  }
  return result;
}

Use it like this, to sum an array but exit when you hit 99:

reduce([1, 2, 99, 3], (a, b) => b === 99 ? EXIT_REDUCE : a + b, 0);

> 3

There is no way, of course, to get the built-in version of reduce to exit prematurely.

Comments