Skip to curriculum
Jump to the editor

20.1. A circular buffer

Easy
Topics

This question is in

20. Caches and buffers
15–25 min

A log panel keeps the last 1,000 lines, a chart the last 60 seconds of samples, an undo menu the last 20 actions. Each needs a queue with a fixed size where a new item pushes the oldest out. An array with push and shift works, but shift moves every remaining item one slot down: at 1,000 items and many updates a second, that is wasted work. A circular buffer (ring buffer) keeps the items in a fixed array and moves an index instead.

Write a CircularBuffer class in circular-buffer.js.

Signature

JAVASCRIPT
class CircularBuffer {
  constructor(capacity)  // a positive integer
  get capacity()         // the number of slots
  get size()             // how many items it holds
  isFull()               // size === capacity
  push(value)            // adds the newest item; returns the item dropped, or undefined
  shift()                // removes and returns the oldest item, or undefined
  at(index)              // 0 is the oldest, -1 the newest; undefined out of range
  toArray()              // oldest to newest, in a new array
  clear()                // removes every item
  [Symbol.iterator]()    // for...of and spread, oldest to newest
}

Requirements

  1. The constructor throws RangeError unless capacity is a positive integer (a number, not a string).
  2. A new buffer is empty: size 0, not full, toArray() gives [].
  3. push adds the newest item and returns undefined while there is room.
  4. On a full buffer, push drops the oldest item, stores the new one, and returns the dropped item. size never exceeds capacity.
  5. shift removes and returns the oldest item; on an empty buffer it returns undefined and changes nothing.
  6. Any mix of push and shift keeps the right order, however many times the positions wrap around.
  7. at(index) works like Array.prototype.at: negative indexes count from the newest, the index is truncated (NaN is 0), and out of range gives undefined.
  8. toArray() returns a new array each time; changing it does not change the buffer.
  9. clear() empties the buffer, and it keeps working afterwards.
  10. The buffer is iterable from oldest to newest.
  11. undefined and null are items like any other.
  12. push, shift and at take constant time: no Array.prototype.shift, unshift or splice.

Examples

JAVASCRIPT
const recent = new CircularBuffer(3);
recent.push("a"); recent.push("b"); recent.push("c");  // undefined each time
recent.push("d");    // "a" (dropped)
recent.toArray();    // ["b", "c", "d"]
recent.at(-1);       // "d"
JAVASCRIPT
recent.shift();      // "b"
recent.size;         // 2
[...recent];         // ["c", "d"]
JAVASCRIPT
new CircularBuffer(0);    // RangeError
new CircularBuffer(1).at(5);  // undefined

Environment

  • Plain JavaScript in a browser page; the tests create new CircularBuffer(…) from circular-buffer.js.
  • One test replaces Array.prototype.shift, unshift and splice with functions that throw, and runs 300,000 operations on a buffer of 50,000.
  • Out of scope: growing the capacity later, and changing the buffer while iterating over it.

Hints

  1. If you never move items, what do you need to remember to know where the oldest one is?
  2. When the buffer is full, which slot does the next item go into?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…