JavaScript Data Structures: Queue (pt. 2)
In last week’s blog post, I introduced the JavaScript data structure — the queue.
As a quick recap, a queue is an ordered list with the “First In / First Out” (FIFO) principle. Items that enter the queue first will leave/be removed from the queue first.
Queues have three main operations — enqueue (inserting an element), dequeue (removing an element), and peek (returning the first element in the queue without modifying the queue).
Today, I will be discussing how to implement a basic queue with an array. I will also discuss how to use enqueue/dequeue/peek.
Implementing a Queue (w/ an Array)
To implement a queue, we will be using an array.
class Queue {
constructor() {
this.items = [];
}
}var newQueue = new Queue();
console.log(newQueue) //=> []
Enqueue/Dequeue
Next, to add and remove elements, we will need to implement the corresponding functions within the Queue class.
class Queue {
...
// ADDING an element
enqueue(element) {
this.items.push(element);
}
// this will "push" the element to the end of the list // REMOVING an element-requires checking to see if it's empty
dequeue() {
if(this.items.length !== 0) {
this.items.shift();
}
}
// "shifting" an element will remove the first element in the list
}
Here, we use enqueue
to add an element to the end of the queue (or as the first element if the list is empty). We also use dequeue
to remove the first element of the queue.
Peek
To return the first element of the queue without modifying it, we can create a function called peek
.
class Queue {
... peek() {
if (this.items.length === 0) {
return "Queue is empty"
}
return this.items[0];
}
}
Here, we check again to see if the queue is empty or not. If it is empty, we simply return the statement “Queue is empty” to indicate there are no items in the queue.
If it’s not empty, it will pass over the if
statement and catch the return
, thus returning the first item in the queue. This will not modify the queue at all.
And there you have it! A simple way to implement a queue with basic adding/removing functions labeled as enqueue
and dequeue
.