Starting with ECMAScript 2015, The WeakSet objects are collections of objects. Just as with Sets, each object in a WeakSet may occur only once; all objects in a WeakSet’s collection are unique.
Create a WeakSet:
const myWeakSet = new WeakSet()
Appends value to the WeakSet object
Values of WeakSets are of the type Object only.
Use add(value)
method:
const myWeakSet = new WeakSet() const ob1 = {} const ob2 = {} const ob3 = function(a){return a} const ob4 = {a:1,b:2} const ob5 = {b:2,a:1} const ob6 = {a:1,b:2} myWeakSet.add(ob1) myWeakSet.add(ob2) myWeakSet.add(ob3) myWeakSet.add(ob4) myWeakSet.add(ob5) myWeakSet.add(ob6)
Checking a value exists in a WeakSet
Use has(value)
method:
console.log(myWeakSet.has(ob1)) //true console.log(myWeakSet.has(ob2)) //true console.log(myWeakSet.has(ob3)) //true console.log(myWeakSet.has(ob4)) //true console.log(myWeakSet.has(ob5)) //true console.log(myWeakSet.has(ob6)) //true
Delete a WeakSet value
Use delete(value)
method:
console.log(myWeakSet.delete(ob3)) //true
Size of WeakSet
console.log(WeakSet.size) //5
Instance methods
WeakSet.prototype.add(value)
Appends value to the WeakSet object.
WeakSet.prototype.delete(value)
Removes value from the WeakSet. WeakSet.prototype.has(value) will return false afterwards.
WeakSet.prototype.has(value)
Returns a boolean asserting whether value is present in the WeakSet object or not.