fixed-length-arrays v0.1.1
fixed-length-arrays

Arrays of fixed length
Installation
$ npm install --save fixed-length-arraysUsage
For any of the fixed-length array types, the length is checked against the
property with symbolExpectedLength as key upon instantiation. Note that
this does not affect the length-property—one can still set it to any value
one could set it to for the standard constructors.
The symbolExpectedLength-property can also be set via setExpectedLength, a
function also exported by the module.
Using Predefined Fixed-Length Arrays
The module exports, for any Array and the %TypedArray%-constructors, a
constructor named FixedLength*. So, for example, FixedLengthArray for
Array and FixedLengthUint8Array for Uint8Array.
One can instead also import the constructors from equivalently-named files,
which can be found in fixed-length-arrays/lib/; however, those don’t include
symbolExpectedLength and setExpectedLength, which can instead be imported from
fixed-length-arrays/lib/factory.
const {
symbolExpectedLength,
setExpectedLength,
FixedLengthArray
} = require("fixed-length-arrays");
// Or, equivalently:
const {
symbolExpectedLength,
setExpectedLength
} = require("fixed-length-arrays/lib/factory");
const FixedLengthArray = require("fixed-length-arrays/lib/FixedLengthArray");
class Example extends FixedLengthArray {}
// Every new instance of Example with a different length will throw
Example[symbolExpectedLength] = 5;
// Or, equivalently:
setExpectedLength(Example, 5);
new Example(10); // Throws
new Example(0); // Throws
new Example([0]); // Throws
new Example(); // Doesn’t throw and has length 5
new Example(5); // Doesn’t throw
Example.of(0, 1, 2); // Throws
Example.of(0, 1, 2, 3, 4); // Doesn’t throw
Example.from([0, 1, 2]); // Throws
Example.from([0, 1, 2, 3, 4]); // Doesn’t throwCreating Custom Fixed-Length Array-Types
fixed-length-arrays/factory exports a factory-function for constructors with
fixed length.
const factory = require("fixed-length-arrays");
const SomeFixedLengthExample = factory(Example, {
expectedLength: 15,
name: "SomeName"
});
SomeFixedLengthExample[factory.symbolExpectedLength]; // 15
SomeFixedLengthExample.name; // "SomeName"
new SomeFixedLengthExample(0); // Throws
new SomeFixedLengthExample(10); // Throws
new SomeFixedLengthExample(15); // Doesn’t throwLicense
MIT © Malte-Maurice Dreyer