Queue in Javascript
by Geethalakshmi[ Edit ] 2010-09-16 21:17:47
Queue in Javascript
A queue follows the First-In First-Out (FIFO) paradigm: the first item added will be the first item removed. An array can be turned into a queue by using the push() and shift() methods. push() inserts the passed argument at the end of the array, and shift() removes and returns the first item. Let's see how to use them:
var queue = [];
queue.push(2); // queue is now [2]
queue.push(5); // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]
alert(i); // displays 2
It's worth noting that Array also has a function named unshift(). This function adds the passed item to the beginning of an array. So a stack can also be simulated by using unshift()/shift(), and a queue can be simulated by using unshift()/pop().
If all these function names are confusing, you may create aliases with your own names. For example, to create a queue with methods named add and remove:
var queue = [];
queue.add = queue.push;
queue.remove = queue.shift;
queue.add(1);
var i = queue.remove();
alert(i);