0.0.2 • Published 3 years ago

weak-merge v0.0.2

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
3 years ago

Install

$ npm i weak-merge

Usage

import { mergeWeakSets, mergeWeakMaps } 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))
//=> 1

See 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

OperationNative WeakSetMerge of n native WeakSet instances
addO(1)O(1)
deleteO(1)O(1)
hasO(1)O(n)

WeakMap Time Complexity

OperationNative WeakMapMerge of n native WeakMap instances
deleteO(1)O(1)
getO(1)O(n)
hasO(1)O(n)
setO(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

Apache 2.0

This is not an official Google product.