@beenotung/tslib
Version:
utils library in Typescript
44 lines (43 loc) • 1.02 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RingBuffer = void 0;
const array_1 = require("./array");
class RingBuffer {
size;
xs;
start = 0;
end = 0;
count = 0;
constructor(size = (0, array_1.getMaxArraySize)()) {
this.size = size;
this.xs = new Array(size);
this.end = size - 1;
}
get length() {
return this.count;
}
enqueue(x) {
if (this.count === this.size) {
throw new Error('buffer is full');
}
this.count++;
this.end = (this.end + 1) % this.size;
this.xs[this.end] = x;
}
push(x) {
this.enqueue(x);
}
dequeue() {
if (this.count === 0) {
throw new Error('buffer is empty');
}
this.count--;
const x = this.xs[this.start];
this.start = (this.start + 1) % this.size;
return x;
}
unshift() {
return this.dequeue();
}
}
exports.RingBuffer = RingBuffer;