Fun with Simple JavaScript Queues

SquirrelFish.jpg

I was adding a few things to my web app today and needed to implement a simple FIFO queue in JavaScript, but didn't need a fancy class. Thankfully, the JavaScript Array has everything I need. There's already a push() and pop() which make a LIFO queue, and if you use shift() you get the first element in the array which makes it a FIFO queue. Pretty sweet.

But the really cool part was making a queue of complex data structures. Sure, you can make JavaScript objects, and push() and shift() them, but you can make a queue that has multiple queues in it and then in your own push() method, you push the different parts onto the different queues.

Say I needed to have a queue of names and sizes. I could have the code at the top of my page:

  var  myQueue = { name: new Array(), size: new Array() };

and then later have the method:

  function push(name, size) {
    myQueue.name.push(name);
    myQueue.size.push(size);
  }

So that if we need to process what's in the queue you might say:

  function processAll() {
    while (myQueue.name.length > 0) {
      doIt(myQueue.name.shift(), myQueue.size.shift());
    }
  }

This is a really slick little way to handle data structures. This isn't real rocket science, but it's fast, simple, and for my application, it's just what I needed. Make a queue, populate it with event data, and then process them en masse.

Not bad.