DictUnit
DictUnit is a type of Unit that only accepts plain, non-null, non-Array, key-value based
object
data type as its value. It ensures that at any point of time the value would always be a dictionary object
.
It's loosely based on Map. DictUnit has some similar methods as the Map, but that's where the similarities end. For one thing, the keys in DictUnit value can only be of type string
since the underlying data structure is still a simple object
not a Map
.It borrows some Map.prototype methods like
set
, has
, get
etc.
However, these methods aren't exactly the same, there are some differences as we explained above.It also implements non-deprecated Object.prototype methods like
hasOwnProperty
, and redirects them to the stored object
value inside the Unit, so when you call DictUnit.hasOwnProperty('prop')
, it'll be executed on the Unit's value instead of the Unit instance itself. But there's probably no need to call it, you can just use DictUnit.has('prop')
instead.It also borrows some static methods from Object like
assign
and entries
, and implements them as instance members assign
and objectEntries
, respectively. These methods operate on the stored object value instead of the Unit instance itself. | |
Default value | {} |
Value data type | plain dictionary object |
DictUnit can not be used as a drop-in replacement for a dictionary
object
or Map
. You can not directly assign or access properties like unit[k] = v
instead, you have to use unit.set('k', v)
and unit.get('k')
, respectively. Unlike a Map, the keys can only be of type string
as the underlying data structure is still a simple object
. See the below comparisons for more clarity.// initialization
const obj = {a: 1}; // an object literal
const map = new Map([['a', 1]]); // a map with a key:value pair 'a':1
const unit = new DictUnit({initialValue: {a: 1}}); // value is {a: 1}
obj === map // false
obj === unit // false
map === unit // false
typeof obj === 'object' // true
typeof map === 'object' // true
typeof unit === 'object' // true
unit instanceof Map // false
// adding a property
obj.b = 2;
map.set('b') = 2;
unit.set('b') = 2; // this is reactive, creates and dispatches a new object
map.set(obj, unit) // works
map.get(obj) // returns unit
unit.set(obj, map) // won't work, the key has to be a number or string
// additionally, non serialzable values are not recommended,
// when you configure the Unit to be immutable,
// the Unit will create a clone of the value but the Map will not be cloned.
// And when you configure the Unit to be persistent,
// the Unit will save it to localStorage using JSON.stringify but Map doesn't
// work with JSON.stringify, it simply becomes "{}".
map.clear() // clears all the key-value pairs
unit.clearValue() // clears the value and emits the default value {},
// this is similar to map.clear()
unit.clear() // clears the value and emits the default value ie: empty {},
// it also clears the cache, and unfreezes the unit
Last modified 2yr ago