UNPKG

rc-js-util

Version:

A collection of TS and C++ utilities to help writing performant and correct applications, achieved through strict typing and (removable) invariant checking.

53 lines 1.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CircularBuffer = void 0; const array_copy_into_js_1 = require("../array/impl/array-copy-into.js"); /** * @public * Presents an array as if it were circular, going past the end or start loops around. * * @remarks * Supports negative indexes. */ class CircularBuffer { static createEmpty(size) { return new CircularBuffer(new Array(size)); } static createOne(initialValues) { return new CircularBuffer(initialValues); } clone() { const clone = CircularBuffer.createEmpty(this.size); (0, array_copy_into_js_1.arrayCopyInto)(this.values, clone.values); return clone; } getValue(index) { return this.values[this.getAdjustedIndex(index)]; } setValue(index, value) { this.values[this.getAdjustedIndex(index)] = value; } /** * returns the value stored at the index and sets the provided value */ getSetValue(index, value) { const adjustedIndex = this.getAdjustedIndex(index); const previousValue = this.values[adjustedIndex]; this.values[adjustedIndex] = value; return previousValue; } constructor(values) { this.values = values; this.size = values.length; } getAdjustedIndex(index) { const length = this.values.length; const remainder = index % length; if (remainder >= 0) { return remainder; } return length + remainder; } } exports.CircularBuffer = CircularBuffer; //# sourceMappingURL=circular-buffer.js.map