generic-circular-buffer
v0.1.1
Published
Simple Circular Buffer implementation, with sensible typing
Downloads
8
Readme
There are plenty of Circular Buffer implementations for Javascript. Many do not support Typescript, which makes them annoying to use. Others have poor documentation.
This may not be the fastest implementation out there, but it sure makes the most sense and is super easy to use.
Easy to use:
const cb = new CircularBuffer(3);
// Array has length 3 but all elements are initially empty/undefined
cb.push(100);
// The array is now technically [undefined,undefined,100]
console.log(cb.getAll());
// [100] (cb.getAll() strips out the empty slots)
cb.push(200);
cb.push(300);
console.log(cb.getAll());
// [100,200,300];
cb.push(400);
console.log(cb.getAll());
// [200,300,400]
// Note how the array elements have been shifted, to keep the same capacityWorks with Typescript generics:
const cb = new CircularBuffer<string>(3);
// We explicitly set the type of elements we expect in the Buffer
cb.push(3);
// Argument of type 'number' is not assignable to parameter of type 'string'
cb.push("test");
// Fine