UNPKG

websocket-ts

Version:

<div> <div align="center"> <img src="https://raw.githubusercontent.com/jjxxs/websocket-ts/gh-pages/websocket-ts-logo.svg" alt="websocket-ts" width="300" height="65" /> </div> <p align="center"> <img src="https://github.com/jjxxs/websocket-ts

57 lines 2.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RingQueue = void 0; /** * A ring queue is a queue that has a fixed capacity. When the queue is full, the oldest element is * removed to make room for the new element. Reading from a ring queue will return the oldest * element and effectively remove it from the queue. */ var RingQueue = /** @class */ (function () { function RingQueue(capacity) { if (!Number.isInteger(capacity) || capacity <= 0) { throw new Error("Capacity must be a positive integer"); } this.elements = new Array(capacity + 1); // +1 to distinguish between full and empty this.head = 0; this.tail = 0; } RingQueue.prototype.add = function (element) { this.elements[this.head] = element; this.head = (this.head + 1) % this.elements.length; if (this.head === this.tail) { this.tail = (this.tail + 1) % this.elements.length; } }; RingQueue.prototype.clear = function () { this.head = 0; this.tail = 0; }; RingQueue.prototype.forEach = function (fn) { for (var i = this.tail; i !== this.head; i = (i + 1) % this.elements.length) { fn(this.elements[i]); } }; RingQueue.prototype.length = function () { return this.tail === this.head ? 0 : this.tail < this.head ? this.head - this.tail : this.elements.length - this.tail + this.head; }; RingQueue.prototype.isEmpty = function () { return this.head === this.tail; }; RingQueue.prototype.peek = function () { return this.isEmpty() ? undefined : this.elements[this.tail]; }; RingQueue.prototype.read = function () { var e = this.peek(); if (e !== undefined) { this.tail = (this.tail + 1) % this.elements.length; } return e; }; return RingQueue; }()); exports.RingQueue = RingQueue; //# sourceMappingURL=ring_queue.js.map