https://github.com/webreflection/not-so-weak
Iterable WeakMap, WeakSet and WeakValue
https://github.com/webreflection/not-so-weak
Last synced: over 1 year ago
JSON representation
Iterable WeakMap, WeakSet and WeakValue
- Host: GitHub
- URL: https://github.com/webreflection/not-so-weak
- Owner: WebReflection
- License: isc
- Created: 2023-01-26T09:54:54.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-07-14T13:52:47.000Z (about 3 years ago)
- Last Synced: 2025-03-27T14:11:17.155Z (over 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 53.7 KB
- Stars: 37
- Watchers: 2
- Forks: 1
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Not So Weak
[](https://github.com/WebReflection/not-so-weak/actions) [](https://coveralls.io/github/WebReflection/not-so-weak?branch=main)
**Social Media Photo by [Pete Nuij](https://unsplash.com/@pete_nuij) on [Unsplash](https://unsplash.com/)**
Iterable [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) (*WKey*) and [WeakSet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) (*WSet*) through [FinalizationRegistry](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry) and [WeakRef](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef) primitives, reimplementing also the [WeakValue](https://github.com/WebReflection/weak-value#readme) (*WValue*) module, including the optional *callback* for collected values.
```js
// const {WSet, WKey, WValue} = require('not-so-weak');
import {WSet, WKey, WValue} from 'not-so-weak';
// class WSet extends WeakSet implements Set {}
// class WKey extends WeakMap implements Map {}
// class WValue extends Map {}
// node --expose-gc example
const ws = new WSet([{}]);
const wm = new WKey([[{}, 'value']]);
const wv = new WValue;
wv.set('value', {}, function (key) {
console.assert(this === wv);
console.assert(key === 'value');
console.log(key, 'value collected');
});
console.assert(ws.size === 1);
console.assert(wm.size === 1);
console.assert([...wm.values()][0] === 'value');
console.assert([...wv.keys()][0] === 'value');
setTimeout(() => {
gc();
console.assert(ws.size === 0);
console.assert(wm.size === 0);
console.assert(wv.size === 0);
});
```
### Suitable For
* Weak key/value based state/store
* Server Side related tasks that can't bother with manual removal of weakly referenced entries
* every case where you end up swapping to `Map` or `Set` because you realize you cannot iterate over their *Weak* counterpart
* every case where you think there's a memory leak due possibly missing `weakThing.delete(ref)` operations
### Not Suitable For
* raw performance or benchmarks against `Map` or `Set`
* every case where `weakThing.delete(ref)` is already handled by the library or framework logic