Implement a FIFO Queue class with O(1) enqueue and dequeue
A queue is first-in, first-out (FIFO): items leave in the same order they arrived. Job runners, BFS traversals, and request buffers all rely on one. The obvious JavaScript version, array.push plus array.shift, hides a cost: shift moves every remaining element, so each dequeue can be O(n).
Implement a Queue class where every operation is O(1) (amortized):
const queue = new Queue(initialItems?); // optional iterable of starting items, front first
queue.enqueue(item); // adds item at the back, returns the new size
queue.dequeue(); // removes and returns the front item, or undefined if empty
queue.peek(); // returns the front item without removing it, or undefined if empty
queue.size(); // number of items
queue.isEmpty(); // true when size() is 0
queue.clear(); // removes every item
[...queue]; // iterates front to back without removing anything
undefined and null. They count toward size() like any other item.Set, a string, a generator). The first item it yields is the front of the queue. With no argument, the queue starts empty.dequeue() and peek() on an empty queue return undefined and do not throw.for...of, spread, Array.from), front to back. Iterating does not change the queue.Array.prototype.shift, unshift, or splice.const printJobs = new Queue(['cover.pdf']);
printJobs.enqueue('invoice.pdf'); // => 2
printJobs.enqueue('photo.png'); // => 3
printJobs.peek(); // => 'cover.pdf'
[...printJobs]; // => ['cover.pdf', 'invoice.pdf', 'photo.png']
printJobs.dequeue(); // => 'cover.pdf'
printJobs.dequeue(); // => 'invoice.pdf'
printJobs.size(); // => 1
printJobs.clear();
printJobs.isEmpty(); // => true
printJobs.dequeue(); // => undefined