Implementation of Queue in Javascript
Last Updated :
20 Dec, 2023
In This article, we will be implementing Queue data structure in JavaScript. A Queue works on the FIFO(First in First Out) principle. Hence, it performs two basic operations which are the addition of elements at the end of the queue and the removal of elements from the front of the queue. Like Stack, Queue is also a linear data structure.Â
Note: Assuming a queue can grow dynamically we are not considering the overflow condition Now let’s see an example of a queue class using an array:-Â
To implement a queue data structure we need the following methods:
- enqueue : To add elements at the end of the queue.
- dequeue: To remove an element from the front of the queue.
- peek: To get the front element without removing it.
- isEmpty: To check whether an element is present in the queue or not.
- printQueue: To print the elements present in the queue.
First, we will be implementing the data structure by creating a queue object and defining the methods for it. We will use additional variables and time complexity will be O(1) which will make the execution of functions faster irrespective of the size of the queue. The additional variables keep track of the index of the first and last element so we do not have to iterate the queue at each insertion and deletion.
Implementation:
Javascript
class Queue {
constructor() {
this .items = {}
this .frontIndex = 0
this .backIndex = 0
}
enqueue(item) {
this .items[ this .backIndex] = item
this .backIndex++
return item + ' inserted'
}
dequeue() {
const item = this .items[ this .frontIndex]
delete this .items[ this .frontIndex]
this .frontIndex++
return item
}
peek() {
return this .items[ this .frontIndex]
}
get printQueue() {
return this .items;
}
}
const queue = new Queue()
console.log(queue.enqueue(7))
console.log(queue.enqueue(2))
console.log(queue.enqueue(6))
console.log(queue.enqueue(4))
console.log(queue.dequeue())
console.log(queue.peek())
let str = queue.printQueue;
console.log(str)
|
Output:
Explanation: The insertion and deletion of items are performed in O(1) because of variables frontIndex and backIndex.
Time complexity:
- Enqueuing an element: O(1)
- Dequeuing an element: O(n) (as all the remaining elements need to be shifted one position to the left)
- Accessing the front of the queue: O(1)
Space complexity:Â
O(n), where n is the number of elements in the queue.
We can also create a queue using array and use the inbuilt array methods to implement the queue functions. The only drawback of inbuilt array methods is that they perform operations in O(n) time complexity.
Example: Showing class Queue and it’s constructor.
Javascript
class Queue{
constructor() {
this .items = [];
}
}
|
As in the above definition we have created a skeleton of a queue class which contains a constructor in which we declare an array to implement queue. Hence, with the creation of an object of a queue class this constructor would be called automatically and the array will be declared Let’s implement each of these functions:
Example: JavaScript enqueue() adds an element to the queue.
Javascript
enqueue(element){
this .items.push(element);
}
|
This function adds an element at the rear of a queue. We have used push() method of array to add an element at the end of the queue.
Example: JavaScript dequeue() removes an element from the queue.Â
Javascript
dequeue()
{
if ( this .isEmpty())
return "Underflow" ;
return this .items.shift();
}
|
This function removes an element from the front of a queue . We have used shift method of an array to remove an element from the queue.
Example: JavaScript peek() returns the front/top element of the queue.Â
Javascript
peek()
{
if ( this .isEmpty())
return "No elements in Queue" ;
return this .items[0];
}
|
This function returns the front element of the queue. We simply return the 0th element of an array to get the front of a queue.
In this function we have used the length property of an array and if the array length is 0 then the queue is empty.
Let’s declare some helper method which is quite useful while working with the queue.
Example: JavaScript isEmpty() returns true if the queue is emptyÂ
Javascript
isEmpty() {
return this .items.length == 0;
}
|
Example: JavaScript printQueue() returns all the elements of a queue.Â
Javascript
printQueue()
{
let str = "" ;
for ( var i = 0; i < this .items.length; i++)
str += this .items[i] + " " ;
return str;
}
|
In this method, we concatenate all the elements of the queue in a string and return the string
Note: Different helper methods can be declared in the Queue class as per the requirement.
Implementation
Now let’s use the queue class and its different method described aboveÂ
Javascript
let queue = new Queue();
console.log(queue.dequeue());
console.log(queue.isEmpty());
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.enqueue(60);
console.log(queue.peek());
console.log(queue.dequeue());
console.log(queue.peek());
console.log(queue.dequeue());
console.log(queue.printQueue());
|
Output:
Underflow
true
10
20
[30, 40, 50, 60]
Now once we are done with the implementation of the Queue class we can use it in different applications.
In this problem, we generate different binary numbers from 1 to n.Â
Javascript
function generatePrintBinary(n)
{
let q = new Queue();
q.enqueue( "1" );
while (n-- > 0)
{
let s1 = q.front();
q.dequeue();
console.log(s1);
let s2 = s1;
q.enqueue(s1 + "0" );
q.enqueue(s2 + "1" );
}
}
generatePrintBinary(5);
|
Output:
1
10
11
100
101
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...