Skip to content

Instantly share code, notes, and snippets.

@jonasantonelli
Created July 14, 2021 17:01
Show Gist options
  • Save jonasantonelli/4fcf2728d05ca634be6a2a726917f08e to your computer and use it in GitHub Desktop.
Save jonasantonelli/4fcf2728d05ca634be6a2a726917f08e to your computer and use it in GitHub Desktop.
RingBuffer.ts
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> {
private array: any[];
constructor(capacity) {
this.array = new Array(capacity)
}
peek() {
return this.array[this.array.length - 1];
}
push(value) {
this.array.push(value);
}
pop() {
this.array.pop();
return this;
}
}
// 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