Skip to main content

createCircularBuffer

function createCircularBuffer<T>(capacity, ArrayType): object;

Creates a circular buffer backed by a TypedArray using a "power-of-two size" optimization.

This implementation leaves one slot unused to distinguish between empty and full states:

  • For capacity N, at most N-1 elements can be stored.
  • When full (size N-1), push will overwrite the oldest (tail advances).

Designed for performance:

  • Capacity must be a power of two for fast bitwise operations.
  • Supports any TypedArray constructor (e.g. Float32Array, Uint8Array).
  • All state is encapsulated in closure; no class or prototype.

Example usage:

const buffer = createCircularBuffer<Float32Array>(8, Float32Array);
buffer.push(1.1); buffer.push(2.2); buffer.pop(); // 1.1

Type Parameters

Type Parameter
T extends TypedArray

Parameters

ParameterTypeDescription
capacitynumberBuffer's capacity (must be a power of two, and > 1).
ArrayType(length) => TThe TypedArray constructor (e.g. Float32Array).

Returns

CircularBuffer

NameTypeDefault value
push()(value) => void-
pop()() => T[number] | undefined-
peek()() => T[number] | undefined-
isEmpty()() => boolean-
isFull()() => boolean-
size()() => number-
clear()() => void-
toArray()() => T[number][]-
[iterator]()() => IterableIterator<T[number]>iterator