1

I have a function with nested loops, first is an array loop and inside a forEach loop.

const myFunction = (data: string[][]): boolean => {

  for (const row of data) {
    row.forEach((item, i) => {

      if (!something) {
        return false;
      }
      if (
        !somethingelse
      ) {
        return false;
      }

      return undefined;
    });
  }

  return true;
};

Whenever I return false I would like that myFunction will return false, and only at the end if false wasn't returned, I'd like to return true. However to my understanding since it's nested loops, When I return false, I'm actually breaking out of the loop.

The only solution I thought about is to declare a variable and set it to "false" and then return the result at the end of all loops. However I'm finding that this might not be a good solution since es-lint complains when trying to change variables declared outside of the loop (can cause memory leaks). Is there another way without creating a variable, is there a way to return from a function without solely break out of the loop?

sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • 2
    Why not use another `for/of` loop for that inner loop rather than a `forEach` (which won't allow you to break out of or return when you want)? – Andy Dec 18 '22 at 16:04
  • I see that for/of loop is actually twice as slow than forEach, which means I probably should use forEach twice... Is this the only way (using two for/of loops) ? – sir-haver Dec 18 '22 at 16:06
  • 2
    Is your application performance-sensitive? Twice as slow doesn’t mean much if it goes from 0.1ms to 0.2ms – Slava Knyazev Dec 18 '22 at 16:17

2 Answers2

2

I think for this you could use the .some method on arrays.

const myFunction = (data: string[][]): boolean => {
    const result = data.some(row => 
        row.some((item, i) => {
            if(!something) 
                return false
            else if (!somethingElse)
                return false
            else return true 
      }))
    
    return result
}

This would allow you to iterate through all of the data, if one of the conditions is met to true then the value of result would be true. Else it would be false.

toby
  • 121
  • 5
  • Thanks that's an interesting approach I'll try it out, also throwing for catching and returning false is another way of course – sir-haver Dec 18 '22 at 19:26
1

A "for(;;)" loop or a "for of" are options which don't take away your ability to return early.

Another option is to use "find" to return a specific value from the array, or "some" if you only need to return true/false.

Slava Knyazev
  • 5,377
  • 1
  • 22
  • 43