Skip to content

Instantly share code, notes, and snippets.

@chadaustin
Created February 2, 2016 07:49
Show Gist options
  • Select an option

  • Save chadaustin/2763721e619425a5221c to your computer and use it in GitHub Desktop.

Select an option

Save chadaustin/2763721e619425a5221c to your computer and use it in GitHub Desktop.
export default class RingBuffer<T> {
_max_length: number;
_buffer: T[];
_write_head: number;
_length: number;
constructor(max_length: number) {
this._max_length = max_length;
this._buffer = new Array(max_length);
this._write_head = 0;
this._length = 0;
}
add(...values: T[]) {
values.forEach(value => {
this._buffer[this._write_head] = value;
this._write_head = (this._write_head + 1) % this._max_length;
this._length = Math.min(this._length + 1, this._max_length);
});
}
get_all(): T[] {
let start = this._write_head;
let first_slice = this._buffer.slice(start, this._length);
let second_slice = this._buffer.slice(0, start);
return first_slice.concat(second_slice);
}
get_last(count: number): T[] {
return this.get_all().slice(-count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment