'How to convert a nested for of loop into a custom iterator?

I have the following code:

function* getPossibleCollidersWith(shape) {
  for (let square of retrieve(shape)) {
    for (let neighbor of square) {
      yield neighbor;
    }
  }
}

This works, but uses generators and yield, which is very slow. I've benchmarked it using Chrome's profiler and it is significantly less performant than removing the generator and just iterating through the nested loop in the client code.

However, it's a lot of boilerplate to do a nested loop every time I want to get a shape's neighbors. I would like to create a custom iterator to see if that has better performance than the generator function, but all the examples I see are rather complex and involve keeping track of indicies, null values, etc.

Is there a simple way to convert the above code into a custom iterator? Ideally I'd like to keep using for of loops to return each element, but all the examples I see online involve error-prone index-tracking.

I would like the client code to look like this, if possible:

for (let neighbor of getPossibleCollidersWith(shape)) {
  // handle neighbor
}


Solution 1:[1]

function* getPossibleCollidersWith(shape) {
  for (let square of retrieve(shape)) {
    yield* square;
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Worldwidebrine