0

I have the same bit of code written in two different ways, and the only difference between them is that one uses a for loop, while the other uses a foreach loop. However, they seem to give different results.

Images of the results can be found at the bottom.

The bit of code checks if the blue rectangles intersect with the purple or the gray ones, and if they do, return false. This bit of code is run each time a new blue rectangle is created

The purpose of this is to make sure no blue rectangles are outside the area delimited by the gray area nor inside the green area

const USE_FOR = true;

// wall.type: string value, possible values: 'bound', 'base', 'random'
// CONFIG.wall.bound_type: 'gray'
// CONFIG.wall.base_type: 'base'

// 'bound' type: gray rectangles
// 'base' type: purple rectangles
// 'random' type: blue rectangles
if (USE_FOR) {
    for (let i = 0; i < walls.length; i++) {
        let wall = walls[i];

        if (wall.type == CONFIG.wall.base_type || wall.type == CONFIG.wall.bound_type) {
            if (isCollision(wall.getArea(), area)) {
                return false;
            }
        }
    }
} else {
    walls.forEach((wall) => {
        if (wall.type == CONFIG.wall.base_type || wall.type == CONFIG.wall.bound_type) {
            if (isCollision(wall.getArea(), area)) {
                return false;
            }
        }
    });
}

return true;

Result from using the for loop

Result from using the foreach loop

tonyvas
  • 21
  • 2
  • 3
    return in for loop exits the outer function. return in foreach loop only exits the anon function inside (which does nothing) – nhahtdh May 13 '20 at 06:47

1 Answers1

0

Instead of using Array.prototype.forEach your can use Array.prototype.some to return when your predicate has matched:

const array = [1, 2, 3, 4, 5];

function demoFor(array, predicate, useFor = true) {
  if (useFor) {
    for (let i = 0; i < array.length; i++) {
      if (predicate(array[i])) return false;
      else console.log(array[i]);
    }
  } else {
    return !array.some((e) => {
      if (predicate(e)) return true;
      else console.log(e);
    });
  }
}
const predicate = (e) => e === 3;
console.log("Using for loop");
demoFor(array, predicate, true);
console.log("Using some");
demoFor(array, predicate, false);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44