Search code examples
javascriptcoffeescript

How do I iterate over a queue, adding and deleting elements as I go?


I want to be able to iterate over a queue, each time adding some new elements to the queue, but removing elements that I have dealt with.

queue = [[0,8],[1,2],[2,4]]

for [x,y] in queue
    for i in [1,2,3]
        # Do something that results in a new coordinate..
        queue.push([newx,newy])

The problem is, I am not sure what the best way to do this would be.

If I delete each element from the array as I iterate, it leaves an empty element in the array.

If I copy the array, empty it by doing queue.length = 0 and then iterate over the copy, that won't work because doing a slice to copy doesn't work when the array contains objects.

What would be the correct way to do this?


Solution

  • What you should do is modify a copy of the array:

    queue2 = queue.slice 0
    
    for [x,y] in queue
      for i in [1,2,3]
        # generate newX and newY
        queue2.push([newx,newy])
    
    queue = queue2
    

    I'm not sure what you mean when you say

    that wont work because doing a slice to copy doesn't work when the array contains objects.

    You may have been misled by something you read elsewhere. Using slice to do an array copy works perfectly well with objects:

    coffee> queue = [[0,8],[1,2],[2,4]]
    [ [ 0, 8 ], [ 1, 2 ], [ 2, 4 ] ]
    coffee> queue.slice 0
    [ [ 0, 8 ], [ 1, 2 ], [ 2, 4 ] ]
    

    What it won't do is do a deep copy of the objects stored by the array. But since you're just doing insertions and deletions to queue, that's perfectly acceptable.