UNPKG

cirbuf

Version:

A tiny and fast circular buffer

38 lines (37 loc) 966 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CircularBuffer = void 0; class CircularBuffer { #data; #next = 0; #overflow = false; #maxSize; constructor(maxSize) { this.#data = new Array(maxSize); this.#maxSize = maxSize; } get maxSize() { return this.#maxSize; } get size() { return this.#overflow ? this.#maxSize : this.#next; } push(value) { this.#data[this.#next] = value; if (this.#next === this.#maxSize - 1) { this.#next = 0; this.#overflow = true; } else { this.#next += 1; } } toArray() { if (!this.#overflow) { // Create a copy of the array return this.#data.slice(0, this.#next); } return this.#data.slice(this.#next).concat(this.#data.slice(0, this.#next)); } } exports.CircularBuffer = CircularBuffer;