Understanding Queue Data Structure in JavaScript ??
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
A queue is a linear data structure that follows the FIFO (First-In, First-Out) principle. This means that the first element added to the queue is the first one to be removed, similar to how people line up in a queue at a ticket counter.
Applications of Queues
Queue Operations
There are several key operations associated with queues:
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
if (this.isEmpty()) {
return null;
}
return this.items.shift();
}
isEmpty() {
return this.items.length == 0;
}
peek() {
if (this.isEmpty()) {
return 'No elements in Queue';
}
return this.items[0];
}
size() {
return this.items.length;
}
printQueue() {
console.log(this.items.toString());
}
}
const queue = new Queue();
console.log(queue.isEmpty());
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.size());
queue.printQueue();
queue.dequeue();
queue.printQueue();
queue.dequeue();
queue.printQueue();