ListUnit
ListUnit is a type of Unit that only accepts array data type as its value. It ensures that at any point of time the value would always be an array.
It's based on Array. It implements all the Array.prototype methods available in the environment/browser, including polyfills. e.g.: push, pop, join and toString etc. to make working with the stored value a bit easier, when you call these methods they are called on the stored array value instead of ListUnit instance.
It also borrows some static methods from Object like values and entries, and implements them as instance members objectValues and objectEntries, respectively.
See API reference for more details.
​
​
Default value
[]
Value data type
array

ListUnit vs array

ListUnit can not be used as a drop-in replacement for an array. You can not directly assign or access properties like unit[index] = v instead, you have to use unit.set(index, v) and unit.get(index), respectively. See the below comparisons for more clarity.
Apart from that, all the non-mutating methods like map, find, findIndex, etc. work similar to as they would on an array. However mutating-methods have some differences, for one, every mutating method makes the Unit emit a new array instead of mutating the current value.
Also, forEach method has been replaced with forEvery, because the extended Observable class already has a forEach method that is intended for something else entirely. See API reference for more details.
1
// initialization
2
const arr = ['🐠']; // an array literal
3
const unit = new ListUnit({initialValue: ['🐠']}); // value is ['🐠']
4
​
5
arr === unit // false
6
​
7
arr instanceof Array // true
8
unit instanceof Array // false
9
Array.isArray(unit) // false
10
​
11
// setting an item
12
arr[1] = '🐞'
13
unit.set(1) = '🐞' // this is reactive, creates and dispatches a new array
14
​
15
// pushing an item
16
arr.push('🐊')
17
unit.push('🐊') // this is reactive, creates and dispatches a new array
18
​
19
// accessing an item at index 0
20
arr[0]
21
unit.get(0)
22
// or
23
unit.first()
24
​
25
// removing an item at index 1
26
arr.splice(1, 1)
27
unit.splice(1, 1)
28
// or
29
unit.remove(1)
Copied!
Last modified 11mo ago
Copy link