Modify collection while looping through it

127 views Asked by At

I have a collection of objects in TypeScript. Each object has a method called getSubObjects which returns a collection of objects of the same type containing the same method getSubObjects. My requirement is

  1. Have to iterate through the original collection calling getSubObjects of each object in the collection.
  2. For each object returned call getSubObjects again.
  3. Keep on going for each object returned until there is no object

So in my loop I want to do something like the following

objCol.forEach(item => {
  const col = item.getSubObjects();
  if(col){
      objCol.pushRange(col)
  }
});

I don't think this is possible in TypeScript, the only alternative I can think of is to resort to recursion, but I would rather avoid it if there an alternative way in which I can do this.

1

There are 1 answers

3
Benny Halperin On

You can avoid recursion by using a naive loop like the following (I did not run the [pseudo] code myself though):

First add another boolean property processed to each object, initialized false. Then:

const processedAll = () => !objCol.some(o => !o.processed);

while (!processedAll()) {
    const extension = [];
    objCol.forEach(item => {
        if (!item.isProcessed) {
            item.processed = true;
            const col = item.getSubObjects();
            if (col) {
                col.processed = false;
                extension.pushRange(col)
            }
        }
    });
    objCol = [...objCol, extension];
}