Javascript-WeakSet
WeakSet objects are collections of objects. In the WeakSet object, each object in a WeakSet may occur only once. Only all objects in a WeakSet’s collection are unique.
Syntax:
new WeakSet([iterable])
- WeakSets are collections of objects only. It doesn’t contain arbitrary values.
Instance methods:
- WeakSet.prototype.add(value) – Appends a value to the WeakSet object.
- WeakSet.prototype.delete(value) – Remove the specified object from the javascript WeakSet object.
- WeakSet.prototype.has(value) – WeakSet object contains the specified object element.
- A WeakSet object contains unique objects only.
- No reference to a stored object and they are targeted to garbage collection.
Using the WeakSet object:
const ws = new WeakSet();
const foo = {};
const bar = {};
ws.add(foo);
ws.add(bar);
ws.has(foo); // true
ws.has(bar); // true
ws.delete(foo); // removes foo from the set
ws.has(foo); // false, foo has been removed
ws.has(bar); // true, bar is retained