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.

49 lines 1.45 kB
import { arrayCopyInto } from "../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. */ export 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); 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; } } //# sourceMappingURL=circular-buffer.js.map