Skip to content

Commit 962cdea

Browse files
committed
add default callback support
1 parent 164c2a7 commit 962cdea

File tree

6 files changed

+112
-3660
lines changed

6 files changed

+112
-3660
lines changed

README.md

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,26 @@ A class that represents an array where missing elements return a specified defau
1111
The built-in JavaScript `Array` class automatically returns `undefined` when you attempt to access a missing element. Here's an example:
1212

1313
```js
14-
const items = [1, , 3];
14+
const items = [1, ,3];
1515
console.log(items[1]); // undefined
1616
```
1717

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

2020
```js
21-
const items = new ArrayWithDefault({
22-
default: 0
23-
elements: [1, , 3]
21+
const items1 = new ArrayWithDefault({
22+
default: 0,
23+
elements: [1, ,3]
2424
});
2525

26-
console.log(items[1]); // 0
26+
console.log(items1[1]); // 0
27+
28+
const items2 = new ArrayWithDefault({
29+
default: (index) => ({ id: index }),
30+
elements: [{ id: 0 }, ,{ id: 2 }]
31+
});
32+
33+
console.log(items2[1]); // { id: 1 }
2734
```
2835

2936
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.
@@ -34,7 +41,7 @@ The primary use case for this class is when an array is an optional argument for
3441

3542
Install using [npm][npm] or [yarn][yarn]:
3643

37-
```
44+
```bash
3845
npm install @humanwhocodes/array-with-default --save
3946

4047
# or
@@ -79,6 +86,7 @@ import { ArrayWithDefault } from "https://cdn.skypack.dev/@humanwhocodes/array-w
7986
After importing, create a new instance of `ArrayWithDefault`. The constructor expects one object argument with the following properties:
8087

8188
* `default` **(required)** - the default value to return for the missing items.
89+
* Note: can be a callback: `(index) => any`
8290
* `elements` - an optional iterable object used to populate the array.
8391
* `length` - an optional value to set the array's `length` property to.
8492
* `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.

0 commit comments

Comments
 (0)