AniUI Academy

A circular buffer that keeps the last N entries

mediumData Structures+250 XPPractice

A long-running tab that keeps every console line, every websocket message or every frame timing will eventually eat all the memory it can. A circular buffer fixes the size up front: once it is full, each new write overwrites the oldest entry.

Implement a CircularBuffer class. new CircularBuffer(capacity) takes a positive integer capacity and starts empty. write(value) always stores the value, and returns true if there was free space or false if it overwrote the oldest entry. read() removes and returns the oldest stored value, or undefined when the buffer is empty. size() returns how many values are currently stored, never more than the capacity. isFull() returns true when size() equals the capacity. toArray() returns the stored values as a plain array from oldest to newest, and [] when empty.

Examples

const b = new CircularBuffer(3);
b.write(1); b.write(2); b.write(3);
b.write(4);     // false — overwrote the oldest
b.toArray();    // [2, 3, 4]

Once full, each new write bumps out the oldest entry.

const b = new CircularBuffer(2);
b.write("a"); b.write("b");
b.read();  // "a" — oldest first
b.read();  // "b"
b.read();  // undefined — empty

What it has to do

  • write returns true when there was room and false when it overwrote the oldest entry.
  • Once full, the buffer keeps only the most recent capacity values.
  • read returns values oldest-first and undefined when empty.
  • toArray() lists values oldest to newest without removing them.
  • The buffer is reusable after being drained.

Notes

  • write and read are both O(1); memory is bounded to the capacity you pass in, which is the whole point.
  • A start index plus a count beats juggling two pointers — the write position is always (start + count) % capacity, no special-casing for an empty or full buffer.

Stuck? The javascript course covers everything this challenge needs.

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

Discussion

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

No comments yet. Be the first to say something.