0.1.1 • Published 6 years ago

fixed-length-arrays v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
6 years ago

fixed-length-arrays NPM version Build Status Dependency Status Coverage percentage

Arrays of fixed length

Installation

$ npm install --save fixed-length-arrays

Usage

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 throw

Creating 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 throw

License

MIT © Malte-Maurice Dreyer

0.1.1

6 years ago

0.1.0

6 years ago