A queue for work that must happen in order
Anything that must happen in the order it was asked for goes through a queue: uploads waiting on a connection, toasts waiting for the one on screen to expire, events buffered while the socket reconnects.
Implement a Queue class. It is constructed with no arguments and starts empty. enqueue(value) adds a value to the back and returns the new size as a number. dequeue() removes the value at the front and returns it, or returns undefined when the queue is empty. front() returns the front value without removing it, or undefined when the queue is empty. size() returns how many values are held. isEmpty() returns true when nothing is held and false otherwise.
Examples
const q = new Queue();
q.enqueue("a"); // 1
q.enqueue("b"); // 2
q.front(); // "a"
q.dequeue(); // "a"
q.dequeue(); // "b"First in, first out — front() reads the head without touching it.
const q = new Queue();
q.dequeue(); // undefined
q.front(); // undefined
q.isEmpty(); // trueAn empty queue returns undefined instead of throwing.
What it has to do
dequeuereturns values in the order they were enqueued.enqueuereturns the size of the queue after the value was added.dequeueandfrontreturnundefinedon an empty queue rather than throwing.frontleaves the queue unchanged.- Enqueueing after the queue has drained works normally.
Notes
- An array-backed queue using
.shift()is O(n) per dequeue because every remaining item slides down. A head-pointer or linked-list implementation gets dequeue to O(1). - For small queues the array version is usually fast enough; reach for the pointer version when the queue grows past a few thousand items or churns under high throughput.
Stuck? The javascript course covers everything this challenge needs.
- 1.dequeues in first-in-first-out order
- 2.enqueue returns the new size and front reports the head
- 3.an empty queue reports undefined instead of throwing
- 4.interleaved enqueues keep their place in line
- 5.front does not remove the value
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.