What you're building
A circular buffer (ring buffer) — a fixed-size queue that reuses its own memory. When the write pointer reaches the end of the array, it wraps back to the start. Used everywhere memory allocation must be bounded:
- Audio/video streaming (jitter buffers)
- OS kernel I/O queues (stdin, network packets)
- Log rotation (keep the last N events in memory)
- Producer/consumer pipelines in real-time systems
Requirements
new CircularBuffer(capacity)— allocate a fixed array ofcapacityslotswrite(val)— enqueue a value; thrownew Error("Buffer full")if the buffer is at capacityread()— dequeue the oldest value; thrownew Error("Buffer empty")if emptyisEmpty()— returntrueif no items are storedisFull()— returntrueif the buffer is at capacitysize()— return the current number of stored items
Track the read head, write head, and count. Use modular arithmetic (% capacity) to wrap indices instead of shifting the array.
Stretch goals
- Add
peek()— return the next item to be read without removing it - Add
overwritemode: when full, silently drop the oldest item instead of throwing
What this proves
You can manage fixed-memory data structures with pointer arithmetic — a fundamental systems programming skill interviewers love.
⚡ 60 XP
solution.jsRuns in your browser
Loading editor…
Tests4 to pass
read returns values in FIFO order
isFull and isEmpty flags
write throws when full
wraps around correctly after read+write cycle
Run your code to check these.