AniUI Academy

A queue for work that must happen in order

easyData Structures+150 XPPractice

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();  // true

An empty queue returns undefined instead of throwing.

What it has to do

  • dequeue returns values in the order they were enqueued.
  • enqueue returns the size of the queue after the value was added.
  • dequeue and front return undefined on an empty queue rather than throwing.
  • front leaves 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.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.