Queue
by Sanju[ Edit ] 2009-11-08 15:55:53
Queue
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.
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);
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().
You can also create aliases with your own names.
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);