Created
April 7, 2021 14:35
-
-
Save giulioz/762ae754afae3688cb371532e5bca934 to your computer and use it in GitHub Desktop.
Circular Buffer for TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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