2

A toy example of a pattern I am trying to solve elegantly. In the below algorithm, I would like to immediately return 0 from reduce when I find an element with a value of 0 without visiting the remaining elements.

let factors = [2,3,6,0,9,4,4,4];
function product(arr) {
    return arr.reduce((acc, elem) => (acc * elem), 1);
}

Is there some way to break out of the reduce iteration?

Doug Coburn
  • 2,485
  • 27
  • 24

1 Answers1

-2

You can short circuit reduce by mutating the original array.

let factors = [2, 3, 6, 0, 9, 4, 4, 4];

function product(arr) {
  return arr.reduce((acc, elem, i, array) => (array[i] === 0 ? (arr.length = i, elem) : (acc * elem)), 1);

}
console.log(product(factors))
Rick
  • 1,035
  • 10
  • 18