Skip to content

Instantly share code, notes, and snippets.

@giulioz
Created April 7, 2021 14:35
Show Gist options
  • Save giulioz/762ae754afae3688cb371532e5bca934 to your computer and use it in GitHub Desktop.
Save giulioz/762ae754afae3688cb371532e5bca934 to your computer and use it in GitHub Desktop.
Circular Buffer for TypeScript
export default class CircBuffer<T> {
data: (T | null)[];
start: number = 0;
end: number = 0;
data_inside: number = 0;
constructor(public size: number) {
this.data = new Array(size).fill(null);
}
add(value: T) {
this.data[this.end] = value;
if (this.data_inside == this.size) {
// Buffer full, go forward
this.start = (this.start + 1) % this.size;
this.end = (this.end + 1) % this.size;
} else {
// Buffer not full, move the end
this.end = (this.end + 1) % this.size;
}
if (this.data_inside < this.size) {
this.data_inside++;
}
}
get(i: number) {
const index = (this.start + i) % this.size;
return this.data[index];
}
getLast() {
return this.data[this.end - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment