event-emitters
Version:
62 lines • 2.39 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = void 0;
var INITIAL_CAPACITY = 16;
/**
* An efficient queue implemented with a circular buffer. It implements just enough
* interface to be useful to EventEmitterAsyncIterator.
*/
var Queue = /** @class */ (function () {
function Queue(capacity) {
if (capacity === void 0) { capacity = INITIAL_CAPACITY; }
this.headIndex = 0;
this.tailIndex = -1;
// writing to this would corrupt the Queue but disallowing it would incur a performance hit
this.length = 0;
this.buffer = new Array(capacity);
}
Queue.prototype.enqueue = function (item) {
if (this.length === this.buffer.length) {
var prevCapacity = this.buffer.length;
this.buffer.length *= 2;
if (this.headIndex / prevCapacity <= 0.5) {
if (this.headIndex !== 0) {
// move elements before head after tail
for (var i = 0; i < this.headIndex; ++i) {
this.buffer[prevCapacity + i] = this.buffer[i];
delete this.buffer[i];
}
this.tailIndex += prevCapacity;
}
}
else {
for (var i = this.tailIndex + 1; i < prevCapacity; ++i) {
this.buffer[prevCapacity + i] = this.buffer[i];
delete this.buffer[i];
}
this.headIndex += prevCapacity;
}
}
this.tailIndex = (this.tailIndex + 1) % this.buffer.length;
this.buffer[this.tailIndex] = item;
++this.length;
};
Queue.prototype.dequeue = function () {
if (this.length === 0) {
throw new Error('Cannot dequeue from empty Queue');
}
--this.length;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var item = this.buffer[this.headIndex];
delete this.buffer[this.headIndex];
this.headIndex = (this.headIndex + 1) % this.buffer.length;
return item;
};
// clear the buffer and leave a corrupt useless buggy object remaining
Queue.prototype.destroy = function () {
this.buffer.length = 0;
};
return Queue;
}());
exports.Queue = Queue;
//# sourceMappingURL=Queue.js.map