Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
export class RingBuffer {
constructor(capacity, data = []) {
this._capacity = capacity;
this._buffer = new Array(this._capacity);
this._writeIndex = 0;
this._readIndex = 0;
this._msgsReceived = 0;
this._lastMeasurement = performance.now();
this._msgsSinceLast = 0;
if (data && data.length > 0) {
for (let i = 0; i < data.length; i++) {
this.write(data[i]);
}
}
}
size() {
if (this._writeIndex + 1 === this._readIndex) {
return this._capacity;
} // buffer is full
// Otherwise, buffer not full, calculate size
return this._writeIndex >= this._readIndex
? this._writeIndex - this._readIndex
: this._capacity - this._readIndex + this._writeIndex;
}
msgsReceived() {
return this._msgsReceived;
}
msgsPerSecond() {
const elapsedS = (performance.now() - this._lastMeasurement) / 1000;
this._lastMeasurement = performance.now();
const result = this._msgsSinceLast / elapsedS;
this._msgsSinceLast = 0;
return result;
}
write(value) {
this._msgsReceived++;
this._msgsSinceLast++;
if (this.size() < this._capacity) {
// not at capacity yet
this._writeIndex = this.next(this._writeIndex);
this._buffer[this._writeIndex] = value;
}
}
read() {
if (this.size() > 0) {
// something available to read
this._readIndex = this.next(this._readIndex);
return this._buffer[this._readIndex];
}
}
next(i) {
++i;
if (i === this._capacity) {
return 0;
} else {
return i;
}
}
}
export default RingBuffer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment