Implementation of Queue in Javascript

In This article, we would be implementing Queue data structure in javascript. A Queue works on the FIFO(First in First Out) principle. Hence, it performs two basic operations that is addition of elements at the end of the queue and 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 queue class using an array:-

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Queue class
class Queue
{
    // Array is used to implement a Queue
    constructor()
    {
        this.items = [];
    }
                  
    // Functions to be implemented
    // enqueue(item)
    // dequeue()
    // front()
    // isEmpty()
    // printQueue()
}

chevron_right


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:

  1. enqueue() – Adds an element to the queue
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // enqueue function
    enqueue(element)
    {    
        // adding element to the queue
        this.items.push(element);
    }

    chevron_right

    
    

    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.

  2. dequeue() – Removes an element from the queue
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // dequeue function
    dequeue()
    {
        // removing element from the queue
        // returns underflow when called 
        // on empty queue
        if(this.isEmpty())
            return "Underflow";
        return this.items.shift();
    }

    chevron_right

    
    

    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.

  3. front() – returns the front element of the queue
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // front function
    front()
    {
        // returns the Front element of 
        // the queue without removing it.
        if(this.isEmpty())
            return "No elements in Queue";
        return this.items[0];
    }

    chevron_right

    
    

    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.

Helper Methods

Let’s declare some helper method which is quite useful while working with the queue.

  1. isEmpty() – Returns true if the queue is empty
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // isEmpty function
    isEmpty()
    {
        // return true if the queue is empty.
        return this.items.length == 0;
    }

    chevron_right

    
    

    In this function we have used the length property of an array and if the array length is 0 then the queue is empty.

  2. printQueue()– Returns all the elements of an queue.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // printQueue function
    printQueue()
    {
        var str = "";
        for(var i = 0; i < this.items.length; i++)
            str += this.items[i] +" ";
        return str;
    }

    chevron_right

    
    

    In this method we concatenate all the elements of the queue in a string and return the string

Note: Different helper method can be declared in Queue class as per the requirement.

Implementation

Now let’s use the queue class and its different method described above

filter_none

edit
close

play_arrow

link
brightness_4
code

// creating object for queue class
var queue = new Queue();
              
  
// Testing dequeue and pop on an empty queue
// returns Underflow
console.log(queue.dequeue());
  
// returns true
console.log(queue.isEmpty());
  
// Adding elements to the queue
// queue contains [10, 20, 30, 40, 50]
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.enqueue(60);
  
// returns 10
console.log(queue.front());
  
// removes 10 from the queue
// queue contains [20, 30, 40, 50, 60]
console.log(queue.dequeue());
  
// returns 20
console.log(queue.front());
  
// removes 20
// queue contains [30, 40, 50, 60]
console.log(queue.dequeue());
  
// printing the elements of the queue
// prints [30, 40, 50, 60]
console.log(queue.printQueue());

chevron_right


Now once we are done with the implementation of Queue class we can use it different applications.

Application : An Interesting Method to Generate Binary Numbers from 1 to n

In this problem we generate different binary numbers from 1 to n.

filter_none

edit
close

play_arrow

link
brightness_4
code

// function to generate binary numbers
function generatePrintBinary(n)
{
    // Create an empty queue of strings
    var q = new Queue();
           
    // Enqueue the first binary number
    q.enqueue("1");
           
    // This loops is like BFS of a tree with 1 as root
    // 0 as left child and 1 as right child and so on
    while(n-- > 0)
    {
        // print the front of queue
        var s1 = q.front();
        q.dequeue();
        console.log(s1);
               
        // Store s1 before changing it
        var s2 = s1;
               
        // Append "0" to s1 and enqueue it
        q.enqueue(s1 + "0");
               
        // Append "1" to s2 and enqueue it. Note that s2 contains
        // the previous front
        q.enqueue(s2 + "1");
     }
}
  
// calling the above function    
// prints [1 10 11 100 101]
generatePrintBinary(5);

chevron_right


This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.