Skip to content

Instantly share code, notes, and snippets.

@Ridermansb
Forked from burtonator/RingBuffer.ts
Last active July 5, 2021 12:00
Show Gist options
  • Save Ridermansb/2258ad248c527ca325ba0b8fff781de3 to your computer and use it in GitHub Desktop.
Save Ridermansb/2258ad248c527ca325ba0b8fff781de3 to your computer and use it in GitHub Desktop.
ring buffer...
import {assert} from 'chai';
/**
* Implement a class named ring buffer with fixed capacity such that
*
* constructor: takes the capacity for the ring buffer
*
* push: adds a value to the ring buffer.
* pop: removes the last value from the ring buffer or undefined if it's empty.
* peek: returns the current value of the most recent value added or undefined if none have been added
*
* If we have too many values (exceeding capacity) the oldest values are lost.
*
* The ordering of the push operations must be kept.
*/
class RingBuffer<T> extends Array {
peek() {
return this[this.length - 1];
}
}
// the following tests must pass
describe("RingBuffer", function() {
it("basic", function() {
const rb = new RingBuffer<number>(3);
assert.isUndefined(rb.peek());
rb.push(1);
assert.isEqual(rb.peek(), 1);
assert.isEqual(rb.pop(), 1);
assert.isUndefined(rb.peek());
});
it("lost data", function() {
const rb = new RingBuffer<number>(3);
rb.push(1);
rb.push(2);
rb.push(3);
rb.push(4);
assert.isEqual(rb.pop(), 4);
assert.isEqual(rb.pop(), 3);
assert.isEqual(rb.pop(), 2);
assert.isUndefined(rb.pop());
});
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment