You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+13-5Lines changed: 13 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -11,19 +11,26 @@ A class that represents an array where missing elements return a specified defau
11
11
The built-in JavaScript `Array` class automatically returns `undefined` when you attempt to access a missing element. Here's an example:
12
12
13
13
```js
14
-
constitems= [1, ,3];
14
+
constitems= [1, ,3];
15
15
console.log(items[1]); // undefined
16
16
```
17
17
18
18
In most cases that is okay, but in some cases you may want an alternate default value returned. The `ArrayWithDefault` class does that:
19
19
20
20
```js
21
-
constitems=newArrayWithDefault({
22
-
default:0
23
-
elements: [1, ,3]
21
+
constitems1=newArrayWithDefault({
22
+
default:0,
23
+
elements: [1, ,3]
24
24
});
25
25
26
-
console.log(items[1]); // 0
26
+
console.log(items1[1]); // 0
27
+
28
+
constitems2=newArrayWithDefault({
29
+
default: (index) => ({ id: index }),
30
+
elements: [{ id:0 }, ,{ id:2 }]
31
+
});
32
+
33
+
console.log(items2[1]); // { id: 1 }
27
34
```
28
35
29
36
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.
@@ -79,6 +86,7 @@ import { ArrayWithDefault } from "https://cdn.skypack.dev/@humanwhocodes/array-w
79
86
After importing, create a new instance of `ArrayWithDefault`. The constructor expects one object argument with the following properties:
80
87
81
88
*`default`**(required)** - the default value to return for the missing items.
89
+
* Note: can be a callback: `(index) => any`
82
90
*`elements` - an optional iterable object used to populate the array.
83
91
*`length` - an optional value to set the array's `length` property to.
84
92
*`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