Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
20.1. A circular buffer
Easy
Topics
This question is in
20. Caches and buffersA 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
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
- The constructor throws
RangeErrorunlesscapacityis a positive integer (a number, not a string). - A new buffer is empty: size 0, not full,
toArray()gives[]. pushadds the newest item and returnsundefinedwhile there is room.- On a full buffer,
pushdrops the oldest item, stores the new one, and returns the dropped item.sizenever exceedscapacity. shiftremoves and returns the oldest item; on an empty buffer it returnsundefinedand changes nothing.- Any mix of
pushandshiftkeeps the right order, however many times the positions wrap around. at(index)works likeArray.prototype.at: negative indexes count from the newest, the index is truncated (NaNis 0), and out of range givesundefined.toArray()returns a new array each time; changing it does not change the buffer.clear()empties the buffer, and it keeps working afterwards.- The buffer is iterable from oldest to newest.
undefinedandnullare items like any other.push,shiftandattake constant time: noArray.prototype.shift,unshiftorsplice.
Examples
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"recent.shift(); // "b"
recent.size; // 2
[...recent]; // ["c", "d"]new CircularBuffer(0); // RangeError
new CircularBuffer(1).at(5); // undefinedEnvironment
- Plain JavaScript in a browser page; the tests create
new CircularBuffer(…)fromcircular-buffer.js. - One test replaces
Array.prototype.shift,unshiftandsplicewith 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
- If you never move items, what do you need to remember to know where the oldest one is?
- 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…