AniUI Academy
medium+250 XPPractice

A circular buffer that keeps the last N entries

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.

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.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.