TypeScript Set and Weakset (with Examples)



TypeScript Set are a bit like maps but they only store keys not key-value pairs.


The Set object lets you store unique values of any type, whether primitive values or object references. Set objects are collections of values, you can iterate its elements in insertion order.

A value in the Set may only occur once; it is unique in the Set’s collection.


Create TypeScript Set

We can create a typescript set using a new keyword like below:

var set = new Set();

we can initialize the typescript Set with an array:

var map = new Map([
     [ "apple" ],
     [ "banana" ],
     [ "carraot"]
 ]);

TypeScript Set Properties and Methods

We can then add entries to typescript set by using the “add” method:

let country = new Set();
set.add('India');
set.add('Aus');
set.add('England');

Alternatively, we can also use the add method to add entries to typescript set like below:

let country = new Set().add('India').add('Aus').add('England');

We can check to see if a key is present using the has method in typescript set like below:

country.has("Aus");//true

We can delete a value from the typescript set like below:

country.delete('Aus');

We can count the number of entries in the set in typescript like below:

country.size; //2

We can empty the entire set with the clear method in TypeScript Set.

country.clear();

Sets can only store unique values, so adding a value a second time has no effect:


Example:

let country = new Set();
country.add('India');
country.size
// 1
country.add('India');
country.size
// 1


Comparing TypeScript Set elements

As with Maps, elements are compared similarly to ===, with the exception of “NaN” being like any other value in typescript set.


Example:

let set = new Set();
set.add(NaN);
console.log(set.size)
console.log(set.has(NaN))
//output:
1
true

Similarly to ===, two different objects are never considered equal.


Example:

let set = new Set();
set.add({});
console.log(set.size)
set.add({});
console.log(set.size)

//output:
1
2

Adding an element a second time has no effect:


Example:

let set = new Set();
set.add("hi");
console.log(set.size)
set.add("hi");
console.log(set.size)
//output:
1
1


Union, intersection, difference in TypeScript

ECMAScript 6 Sets have no methods for computing the union (e.g. addAll), intersection (e.g. retainAll) or difference (e.g. removeAll). This section explains how to work around that limitation.


Union (a ∪ b):

Create a Set that contains the elements of both Set a and Set b.


Example:


var a = new Set([10,20,30,40]);
var b = new Set([40,30,20]);
var union = new Set([...a, ...b]);
console.log(union)

//output:
Set { 10, 20, 30, 40 }

Intersection (a ∩ b):

Create a Set that contains those elements of Set a that is also in Set b.


Example:

var a = new Set([10,20,30,40]);
var b = new Set([40,30,20]);
const intersection = new Set(
    [...a].filter(x => b.has(x)));
console.log(intersection)
//output:
Set { 20, 30, 40 }

Difference (a \ b):

Create a Set that contains those elements of Set a that are not in Set b.


Example:

var a = new Set([10,20,30,40]);
var b = new Set([40,30,20]);
//var union = new Set([...a, ...b]);
var difference = new Set(
    [...a].filter(x => !b.has(x)));
console.log(difference)

//output:
Set { 10 }


Iterate over a TypeScript Set

We can use the for-of loop to loop over items in our typescript set. Easily, we can iterate over a TypeScript set.


Example 1:

let country = new Set(['India', 'Aus', 'England']);
for (let entry of set) {
    console.log(entry);
}

//output:
India
Aus
England

Example 2:

let set = new Set();
let user1 = { name: "John", Technology: "SPFx" };
let user2 = { name: "Pete", Technology:"AngularJS" };
let user3 = { name: "Mary", Technology:"SharePoint"};
set.add(user1);
set.add(user2);
set.add(user3);
console.log( set.size );
for (let user of set) {
  console.log(user.Technology); 
}
//output:
3
SPFx
AngularJS
SharePoint

We can also use the “for each “loop to loop (iterate) over items in typescript set.


Example:

let country = new Set(['India', 'Aus', 'England']);
country.forEach(function(country) {
  console.log(country);
});


TypeScript WeakSet

TypeScript Weakset is a collection similar to Set, which holds unique values; but it only holds Objects and nothing else. If an object which is there in your WeakSet object has no other reference variable left, it will automatically be deleted.

  • The WeakSet object lets you store weakly held objects in a collection.

  • WeakSet objects are collections of objects. An object in the WeakSet may only occur once; it is unique in the WeakSet’s collection.

  • The main differences to the Set object are:

  • In contrast to Sets, WeakSets are collections of objects only and not of arbitrary values of any type.

  • The WeakSet is weak: References to objects in the collection are held weakly. If there is no other reference to an object stored in the WeakSet, they can be garbage collected. That also means that there is no list of current objects stored in the collection. WeakSets are not enumerable.

Syntax:

var myWeakSet= new WeakSet([iterable with only objects]);

Example:

var objweakSet = new WeakSet([{text:"hi"}]);
var obj1 = {text:"hello"};
var obj2 = {text:"bye"};
objweakSet.add(obj1); 
console.log(objweakSet.has(obj1)); 
console.log(objweakSet.has(obj2)); 
objweakSet.add(obj2); 
console.log(objweakSet.has(obj2)); 

//output:
true
false
true


TypeScript WeakSet Properties and Methods

It is analogous to Set, but we may only add objects to WeakSet (not primitives). An object exists in the set while it is reachable from somewhere else. Like Set, Weakset also supports add, has and delete.

  • It does not support size/clear(), keys and iterations.

add(value: T): Appends a new object with the given value to the WeakSet object.


has(value: T): Returns a boolean asserting whether an element is present with the given value in the WeakSetobject or not.


delete(value: T): Removes the element associated to the value. WeakSet.prototype.has(value) will return falseafterwards.


Example:

let messages = [
    {text: "Hi", from: "lakshmi"},
    {text: "How are you?", from: "preeti"},
    {text: "See you soon", from: "bijay"}
];

// fill it with array elements (3 items)
let unreadSet = new WeakSet(messages);

// use unreadSet to see whether a message is unread
console.log(unreadSet.has(messages[2]));

// remove it from the set after reading
console.log(unreadSet.delete(messages[2])); 

//output:
true
true

In this article, we learned about What is Set, WeakSet, and their properties and methods in TypeScript with an example.


Source: SPGuide.com