Implementing a Queue Data Structure in JavaScript
Queues are fundamental data structures that follow the First-In, First-Out (FIFO) principle. This means the first element added to the queue is the first one to be removed. Implementing a queue is useful in scenarios like managing tasks, handling requests, or simulating real-world waiting lines.
Problem Description
You are tasked with implementing a Queue class in JavaScript. This class should provide the following methods:
enqueue(item): Adds anitemto the rear of the queue.dequeue(): Removes and returns the item at the front of the queue. If the queue is empty, it should returnundefined.peek(): Returns the item at the front of the queue without removing it. If the queue is empty, it should returnundefined.isEmpty(): Returnstrueif the queue is empty, andfalseotherwise.size(): Returns the number of items currently in the queue.
The queue should be implemented using an array internally. Ensure your implementation handles edge cases gracefully, particularly when the queue is empty.
Examples
Example 1:
Input:
queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.dequeue());
console.log(queue.peek());
console.log(queue.size());
Output:
1
2
2
Explanation: We enqueue 1, 2, and 3. Then, we dequeue, removing 1. peek() returns the next element (2) without removing it. The size is now 2.
Example 2:
Input:
queue = new Queue();
console.log(queue.dequeue());
console.log(queue.peek());
console.log(queue.isEmpty());
console.log(queue.size());
Output:
undefined
undefined
true
0
Explanation: The queue is initially empty. dequeue() and peek() both return undefined because there's nothing to remove or view. isEmpty() returns true, and size() returns 0.
Example 3: (Edge Case - Dequeueing from an empty queue multiple times)
Input:
queue = new Queue();
queue.dequeue();
queue.dequeue();
Output:
undefined
undefined
Explanation: Demonstrates that repeated calls to dequeue() on an empty queue correctly return undefined without causing errors.
Constraints
- The queue should be implemented using a JavaScript array.
- The
enqueueanddequeueoperations should have an average time complexity of O(1). While array shifting can be O(n) in the worst case, aim for an implementation that minimizes this. - The
peek,isEmpty, andsizeoperations should have a time complexity of O(1). - The queue should handle any data type as an item (numbers, strings, objects, etc.).
- The queue should not use any external libraries.
Notes
Consider how you will manage the front and rear of the queue within the array. Think about how to efficiently add and remove elements while maintaining the FIFO order. While using unshift and pop might seem intuitive, they can lead to performance issues. Consider alternative approaches to optimize for O(1) average time complexity for enqueue and dequeue.