Creating a queue

We are now going to create our own class to represent a queue. Let's start from the basics and declare our class:

function Queue() { 
  //properties and methods go here 
} 

First, we need a data structure that will store the elements of the queue. We can use an array to do it, just like we used it for the Stack class in the previous chapter (you will notice the Queue and Stack class are very similar, just the principles for adding and removing the elements are different):

let items = []; 

Next, we need to declare the methods available for a queue:

  • enqueue(element(s)): This adds a new item (or several items) at the back of the queue.
  • dequeue(): This removes the first item from the queue (the item that is in the front of the queue). It also ...

Get Learning JavaScript Data Structures and Algorithms - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.