@4bitlabs/vector
v1.1.0
Published
A simple, TypedArray-backed resizable vector data-structure for ints, floats, and bigints
Maintainers
Readme
@4bitlabs/vector
A simple, TypedArray-backed resizable vector data-structure.
Installing
Using npm:
$ npm install --save @4bitlabs/vectorDocumentation
Full documentation for the library can be found here
Usage
import { Vector } from '@4bitlabs/vector';
/* Create a resizable vector of float64s */
const floats = new Vector(Float64Array, { initialCapacity: 10 });
floats.push(Math.random());
console.log(floats.pop());
/* Create a resizable vector of bytes */
const bytes = new Vector(Uint8ClampedArray, { initialCapacity: 255 });
bytes.push(0x10);
console.log(bytes.pop());Also included is BigVector for usage with int64 and uint64 sized integers:
import { BigVector } from '@4bitlabs/vector';
const uint64s = new BigVector(BigUint64Array);
uint64s.push(0xffff_ffff_ffff_ffffn);Resize in-place
The default implementations of Vector and BigVector reallocated and copied the underlying
ArrayBuffer on reallocate() and grow(). In certain use-cases, this could cause undesirable
garbage-collection pressure. As of ES2024, support for
in-place, resizable ArrayBuffer
is widely available in both Node and browsers. To use this, provide a maximumCapacity when creating a Vector or BigVector.
import { Vector } from '@4bitlabs/vector';
const vec = new Vector(Uint8Array, { initialCapacity: 16, maximumCapcity: 1_024 });
vec.reallocate(1_024); // growing in-place
vec.reallocate(128); // shrinking in-placeAttempting to resize a Vector beyond its maximum capacity, either through
adding values with push() and pushN() or explicit resizing, will throw an exception.
