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.
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 — emptyWhat it has to do
writereturnstruewhen there was room andfalsewhen it overwrote the oldest entry.- Once full, the buffer keeps only the most recent
capacityvalues. readreturns values oldest-first andundefinedwhen empty.toArray()lists values oldest to newest without removing them.- The buffer is reusable after being drained.
Notes
writeandreadare 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.
- 1.overwrites the oldest entry once full
- 2.reads oldest first and shrinks
- 3.an empty buffer reads undefined
- 4.keeps only the last capacity values after wrapping
- 5.is reusable after being drained
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.