1.0.0 • Published 1 year ago
weak-merge v1.0.0
Install
$ npm i weak-mergeUsage
import { mergeWeakMaps, mergeWeakSets } from 'weak-merge'
const [a, b, c, d] = [{}, {}, {}, {}]
const weakSet1 = new WeakSet([a, b])
const weakSet2 = new WeakSet([c])
const mergedWeakSet = mergeWeakSets(weakSet1, weakSet2)
console.log([a, b, c].map(key => mergedWeakSet.has(key)))
//=> [ true, true, true ]
mergedWeakSet.delete(a)
console.log(mergedWeakSet.has(a))
//=> false
console.log(weakSet1.has(a))
//=> true
mergedWeakSet.add(d)
console.log(mergedWeakSet.has(d))
//=> true
console.log(weakSet1.has(d))
//=> false
const weakMap1 = new WeakMap([
[a, 1],
[b, 2],
])
const weakMap2 = new WeakMap([[c, 3]])
const mergedWeakMap = mergeWeakMaps(weakMap1, weakMap2)
console.log([a, b, c].map(key => mergedWeakMap.get(key)))
//=> [ 1, 2, 3 ]
mergedWeakMap.delete(a)
console.log(mergedWeakMap.has(a))
//=> false
console.log(weakMap1.has(a))
//=> true
mergedWeakMap.set(a, 5)
console.log(mergedWeakMap.get(a))
//=> 5
console.log(weakMap1.get(a))
//=> 1See the TypeScript types for more documentation.
Why?
Merging WeakSet or WeakMap instances is not trivial because they
are not enumerable.
Performance
WeakSet instances returned from mergeWeakSets and WeakMap instances
returned from mergeWeakMaps are not as performant as native WeakSet and
WeakMap instances (due to the lack of a native way to merge or copy WeakSet
and WeakMap instances):
WeakSet Time Complexity
| Operation | Native WeakSet | Merge of n native WeakSet instances |
|---|---|---|
add | O(1) | O(1) |
delete | O(1) | O(1) |
has | O(1) | O(n) |
WeakMap Time Complexity
| Operation | Native WeakMap | Merge of n native WeakMap instances |
|---|---|---|
delete | O(1) | O(1) |
get | O(1) | O(n) |
has | O(1) | O(n) |
set | O(1) | O(1) |
Contributing
Stars are always welcome!
For bugs and feature requests, please create an issue.
For pull requests, please read the contributing guidelines.
License
This is not an official Google product.