class Queue {
constructor() {
this.items = []; // Array to store queue elements
}
// Enqueue: Add an element to the end of the queue
enqueue(element) {
this.items.push(element);
console.log(`${element} added to the queue`);
}
// Dequeue: Remove an element from the front of the queue
dequeue() {
if (this.isEmpty()) {
console.log("Queue is empty, nothing to dequeue");
return null;
}
const removedElement = this.items.shift();
console.log(`${removedElement} removed from the queue`);
return removedElement;
}
// Peek: View the front element without removing it
peek() {
if (this.isEmpty()) {
console.log("Queue is empty, nothing to peek");
return null;
}
return this.items[0];
}
// Check if the queue is empty
isEmpty() {
return this.items.length === 0;
}
// Get the size of the queue
size() {
return this.items.length;
}
// Print the queue elements
printQueue() {
console.log("Queue contents:", this.items.join(", "));
}
}
const queue = new Queue();
// Enqueue elements
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
// Print the queue
queue.printQueue(); // Output: Queue contents: 10, 20, 30
// Peek at the front element
console.log("Front element:", queue.peek()); // Output: Front element: 10
// Dequeue elements
queue.dequeue(); // Output: 10 removed from the queue
queue.dequeue(); // Output: 20 removed from the queue
// Check if the queue is empty
console.log("Is queue empty?", queue.isEmpty()); // Output: Is queue empty? false
// Print the queue again
queue.printQueue(); // Output: Queue contents: 30
/*
run:
10 added to the queue
20 added to the queue
30 added to the queue
40 added to the queue
Queue contents: 10, 20, 30, 40
Front element: 10
10 removed from the queue
20 removed from the queue
Is queue empty? false
Queue contents: 30, 40
*/