WeakishMap
It’s like WeakMap but it supports non-objects.
Installation
Requires Node.js 6.0.0 or above.
npm i weakish-map
API
The module exposes a single class.
Constructor
The constructor supports the following arguments:
- Optional:
items
(iterable): Initial key-value pairs for the map. - Optional: Object argument:
-
StrongMap
(class): Set this if you have a custom Map class you want to use for storing non-objects. Defaults to the built-inMap
. -
strongMap
(function): A callback that creates a new map for storing non-objects. Defaults to a function that creates a newStrongMap
. -
WeakMap
(class): Set this if you have a custom WeakMap class you want to use for storing objects. Defaults to the built-inWeakMap
. -
weakMap
(function): A callback that creates a new weak map for storing objects. Defaults to a function that creates a newWeakMap
.
-
Methods
Instances of this class have the following methods, which behave just like the corresponding methods on Map
and WeakMap
:
get()
set()
has()
delete()
clear()
Instances also have methods which only work on non-objects:
entries()
forEach()
keys()
values()
Example
// Before
const map1 = new WeakMap()
map1.set({}, 'value')
map1.set('key', 'value') // Uncaught TypeError: Invalid value used as weak map key
// After
const WeakishMap = require('weakish-map')
const map2 = new WeakishMap()
map2.set({}, 'value')
map2.set('key', 'value')
map2.get('key') // 'value'
Array.from(map2.keys()) // ['key']