Implement a fixed-size ring buffer that drops the oldest entry
A browser extension keeps the latest console messages so it can attach them to bug reports. Memory must stay flat no matter how chatty the page is, so only the most recent messages are kept, and adding a message must take constant time.
Implement a class RingLog: a fixed-size buffer that keeps the latest values and silently drops the oldest one when it is full.
const log = new RingLog(capacity);
log.push(value) // => the value it evicted, or undefined
log.at(index) // => the value at index, or undefined
log.size() // => number of stored values
log.capacity() // => maximum number of values
log.toArray() // => a new array, oldest to newest
log.clear() // removes every value, keeps the capacity
log.resize(capacity) // changes the capacity
[...log] // iterates oldest to newest
capacity must be a positive integer. The constructor and resize throw a RangeError for anything else (0, -1, 2.5, '3', NaN, Infinity).push(value) adds value as the newest entry. If the buffer was already full, the oldest value is removed and returned. Otherwise push returns undefined. Values can be anything, including undefined and null.push must run in O(1) time. Do not use Array.prototype.shift, unshift, or splice anywhere.at(index): 0 is the oldest stored value and size() - 1 the newest. A negative index counts from the newest: -1 is the newest. Indexes outside the stored range return undefined. Indexes are always integers.toArray() returns a new array every time. Changing it does not change the buffer.resize(capacity) keeps the most recent values that fit, in the same order, and drops the oldest ones. Growing keeps everything.for...of and spread, in the same order as toArray().const log = new RingLog(3);
log.push('boot'); // => undefined
log.push('fetch /me'); // => undefined
log.push('render'); // => undefined
log.push('click #save'); // => 'boot' (evicted)
log.toArray(); // => ['fetch /me', 'render', 'click #save']
log.at(0); // => 'fetch /me'
log.at(-1); // => 'click #save'
log.at(3); // => undefined
log.size(); // => 3
log.resize(2);
[...log]; // => ['render', 'click #save']
log.resize(4);
log.push('error 500'); // => undefined (room after growing)
log.toArray(); // => ['render', 'click #save', 'error 500']
log.clear();
log.size(); // => 0
log.capacity(); // => 4
new RingLog(0); // throws RangeError