Skip to content

Commit

Permalink
add default callback support
Browse files Browse the repository at this point in the history
  • Loading branch information
crazy4groovy committed Nov 6, 2021
1 parent 164c2a7 commit 5ab1f9f
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 3,659 deletions.
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,26 @@ A class that represents an array where missing elements return a specified defau
The built-in JavaScript `Array` class automatically returns `undefined` when you attempt to access a missing element. Here's an example:

```js
const items = [1, , 3];
const items = [1, ,3];
console.log(items[1]); // undefined
```

In most cases that is okay, but in some cases you may want an alternate default value returned. The `ArrayWithDefault` class does that:

```js
const items = new ArrayWithDefault({
default: 0
elements: [1, , 3]
const items1 = new ArrayWithDefault({
default: 0,
elements: [1, ,3]
});

console.log(items[1]); // 0
console.log(items1[1]); // 0

const items2 = new ArrayWithDefault({
default: (index) => ({ id: index }),
elements: [{ id: 0 }, ,{ id: 2 }]
});

console.log(items2[1]); // { id: 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.
Expand Down Expand Up @@ -79,6 +86,7 @@ import { ArrayWithDefault } from "https://cdn.skypack.dev/@humanwhocodes/array-w
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.
* Note: can be a callback: `(index) => any`
* `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.
Expand Down
Loading

0 comments on commit 5ab1f9f

Please sign in to comment.