How to implement a queue in JavaScript
A queue is a data structure that follows FIFO (First In First Out). Think of the queue as a list in which the element that is inserted first will also be accessed first.
Think of it as a ticket counter, where the first person in line will get the first ticket.
We are going to implement the following six operations for our queue:
enqueue()– add an element to the queuedequeue()– remove the first element from the queuepeek()– display the last elementisEmpty()– check if the queue is emptysize()– the total number of elements in the queueclear()– clear all the elements of the queue
// program to implement a queue data structureclass Queue {constructor() {this.queue = [];}enqueue(element) { // add elementreturn this.queue.push(element);}dequeue() {if(this.queue.length > 0) {return this.queue.shift(); // remove first element}}peek() {return this.queue[this.queue.length - 1];}size(){return this.queue.length;}isEmpty() {return this.queue.length == 0;}clear(){this.queue = [];}}let counter = new Queue();// addcounter.enqueue(1);counter.enqueue(2);counter.enqueue(3);// get last elementconsole.log(counter.peek()); // 3// removeconsole.log(counter.dequeue()); // 1console.log(counter.dequeue()); // 2console.log(counter.isEmpty()); // falseconsole.log(counter.size()); // 1counter.clear();console.log(counter.size()); // 0
Complexity of queue operations
We are always going to access the first queue element and add new elements at the end of the queue. To do this, we will use:
- for enqueue –
- for dequeue –