Array with Default Utility
by Nicholas C. Zakas
If you find this useful, please consider supporting my work with a donation.
Description
A class that represents an array where missing elements return a specified default value.
The built-in JavaScript Array class automatically returns undefined when you attempt to access a missing element. Here's an example:
const items = [1, , 3];
console.log(items[1]);
In most cases that is okay, but in some cases you may want an alternate default value returned. The ArrayWithDefault class does that:
const items = new ArrayWithDefault({
default: 0
elements: [1, , 3]
});
console.log(items[1]);
The primary use case for this class is when an array is an optional argument for a function or when an array may have holes.
Usage
Node.js
Install using npm or yarn:
npm install @humanwhocodes/array-with-default --save
# or
yarn add @humanwhocodes/array-with-default
Import into your Node.js project:
const { ArrayWithDefault } = require("@humanwhocodes/array-with-default");
import { ArrayWithDefault } from "@humanwhocodes/array-with-default";
Deno
Import into your Deno project:
import { ArrayWithDefault } from "https://cdn.skypack.dev/@humanwhocodes/array-with-default?dts";
Browser
It's recommended to import the minified version to save bandwidth:
import { ArrayWithDefault } from "https://cdn.skypack.dev/@humanwhocodes/array-with-default?min";
However, you can also import the unminified version for debugging purposes:
import { ArrayWithDefault } from "https://cdn.skypack.dev/@humanwhocodes/array-with-default";
API
After importing, create a new instance of ArrayWithDefault. The constructor expects one object argument with the following properties:
default (required) - the default value to return for the missing items.
elements - an optional iterable object used to populate the array.
length - an optional value to set the array's length property to.
outOfRange - an optional value that, when set to true, indicates that numeric indices after the end of the array should also return the default value.
Here are some examples:
const items = new ArrayWithDefault({
default: 0,
elements: [1, , 3]
});
console.log(items[1]);
console.log(items[10])
items.push(undefined);
console.log(items[3]);
const emptyItems = new ArrayWithDefault({
default: 0,
length: 5
});
console.log(emptyItems[0]);
console.log(emptyItems[1]);
console.log(emptyItems[2]);
console.log(emptyItems[3]);
console.log(emptyItems[4]);
console.log(emptyItems[5]);
const numbers = new ArrayWithDefault({
default: 0,
elements: [1, 2, 3],
outOfRange: true
});
console.log(emptyItems[0]);
console.log(emptyItems[1]);
console.log(emptyItems[2]);
console.log(emptyItems[3]);
console.log(emptyItems[4]);
console.log(emptyItems[5]);
Developer Setup
- Fork the repository
- Clone your fork
- Run
npm install to setup dependencies
- Run
npm test to run tests
License
Apache 2.0