The WeakFlyweightSet
object holds weak references to similar objects.
A weak reference to an object is a reference that does not prevent the object from being reclaimed by the garbage collector. In contrast, a normal (or strong) reference keeps an object in memory.
Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.
The WeakFlyweightSet
is based on Set, WeakRef and FinalizationRegistry objects.
- No dependencies
- TypeScript
- ES2021
- Node.js >=14.6.0
npm i weak-flyweight-set
const set = new WeakFlyweightSet();
let valueObject = {key1: 'value: 1', key2: 'value: 2'};
set.add(valueObject);
// all of the following calls return a reference to the same object
set.get({key1: 'value: 1', key2: 'value: 2'});
set.use({key1: 'value: 1', key2: 'value: 2'});
valueObject = null;
// ...
// GC reclaims space
// ...
// returns undefined
set.get({key1: 'value: 1', key2: 'value: 2'});
// return a reference to a new object
set.use({key1: 'value: 1', key2: 'value: 2'});
Returns the number of values in the WeakFlyweightSet
object.
⚠️ Number of values is not precise due to nature ofFinalizationRegistry
object.
The add()
method adds an object to a WeakFlyweightSet
object.
The get()
method returns a reference to a similar object from a WeakFlyweightSet
object or undefined.
The use()
method returns a reference to a similar object from a WeakFlyweightSet
object or adds the specified object to the set and returns a reference to it.
The has()
method returns a boolean indicating whether a similar object exists or not.
The delete()
method removes a similar object from a WeakFlyweightSet
.
The values()
method returns a new Iterator
object that contains the values for each element in the WeakFlyweightSet
object in insertion order.
The forEach()
method executes a provided function once per each value in the WeakFlyweightSet
object, in insertion order.
The clear()
method removes all elements from a WeakFlyweightSet
object.
WeakFlyweightSet is MIT licensed.