QueueLoading saved progress…

Queue

A queue is a first-in, first-out (FIFO) collection — the same rule as a line at a coffee shop. New items join at the back, and whichever item has been waiting the longest is the next one to come out. You'll build one as a factory function createQueue() that returns an object with four operations.

Implement createQueue(). It returns an object exposing enqueue(item), dequeue(), peek(), and size(). Items leave in the same order they arrived. When the queue is empty, dequeue() and peek() return undefined — they do not throw.

Signature

function createQueue() {
  // returns { enqueue, dequeue, peek, size }
  //
  //   enqueue(item): void   — add to the back
  //   dequeue():     any    — remove + return the front, or undefined if empty
  //   peek():        any    — return the front without removing, or undefined if empty
  //   size():        number — current number of items
}

Examples

const q = createQueue();
q.enqueue('a');
q.enqueue('b');
q.enqueue('c');
q.size();    // 3
q.peek();    // 'a'  (still there)
q.dequeue(); // 'a'
q.dequeue(); // 'b'
q.size();    // 1
// Empty queue: peek and dequeue return undefined, never throw.
const q = createQueue();
q.peek();    // undefined
q.dequeue(); // undefined
q.size();    // 0

// Refill after draining works fine.
q.enqueue(42);
q.dequeue(); // 42

Notes

  • FIFO order — the first value enqueued is the first one dequeued. Not LIFO (that's a stack).
  • Empty behaviorpeek() and dequeue() on an empty queue return undefined. Don't throw.
  • Any value — items can be any JS value: numbers, strings, objects, even null or undefined. The queue doesn't inspect them.
  • size() is a method, not a property. Tests call q.size(), not q.size.
  • No fixed capacity — the queue grows as needed. You don't need to handle a max-size limit.
  • State is private — the internal storage isn't exposed on the returned object. Callers should only see enqueue, dequeue, peek, size.
Loading editor…