Javascript Queues
Creating a JavaScript Queue
A queue is a simple data structure that allows elements to be inserted from one end, called the rear (also called the tail), and deleted from the other end, called the front (also called the head). A queue is called a FIFO Data Structure meaning First in First Out.
Queues are used whenever we need to manage objects in order starting with the first one. Think about adding a song to your Spotify Queue, the first song you add to your queue will be the first song that plays, which means it will the first song out of your queue. A queue in Javascript can be implemented either using an array or a linked list.
A queue has two main operations involving inserting a new element and removing an existing element. The insertion operation is called enqueue, and the removal operation is called dequeue. The enqueue operation inserts an element at the end of the queue, whereas the dequeue operation removes an element from the front of a queue.
To add an element at the end of the array using the push()
function. This function is equivalent to the enqueue operation.
To remove an element from the front of an array using the function. It is the same as the dequeue operation.
Let's Create a Queue
Let’s implement a JavaScript queue data structure by using an array.
The following is the constructor of the queue:
function Queue() {
this.elements = [];
}
The Queue()
constructor function uses an array to store its elements.
The enqueue()
function adds an element at the end of the queue. We use the push()
function of the array object to insert the new element at the end of the queue.
Queue.prototype.enqueue = function (e) {
this.elements.push(e);
};
The dequeue()
function removes an element from the front of the queue. In the dequeue()
function, we use the shift()
function of the array to remove an element at the front of the queue.
//
Queue.prototype.dequeue = function () {
return this.elements.shift();
};
The isEmpty()
function checks if a queue is empty by checking if the length
property of the array is zero.
//
Queue.prototype.isEmpty = function () {
return this.elements.length == 0;
};
The peek()
function accesses the element at the front of the queue without modifying it.
Queue.prototype.peek = function () {
return !this.isEmpty() ? this.elements[0] : undefined;
};
To query the length of a queue, we develop the length()
function:
Queue.prototype.length = function() {
return this.elements.length;
}