Typescript set
Created By: chatGPT
TypeScript provides a built-in Set object, which holds unique values of any type. Unlike arrays, a Set does not allow duplicate entries. This makes it useful for storing data where uniqueness is important. You can create a new Set using the following syntax:
const mySet = new Set<number>();
You can also initialize a Set with an array of values. This is particularly useful when you want to ensure that all values remain unique:
const mySet = new Set<number>([1, 2, 3, 4, 5]);
To add values to a Set, you use the add method. If you try to add a duplicate value, it will simply ignore it:
mySet.add(6);
mySet.add(3); // This will be ignored
You can check the size of the Set using the size property. This is very useful as it immediately gives you the number of unique entries:
console.log(mySet.size); // Outputs: 6
To check if a value exists in the Set, you can use the has method. This method returns a boolean indicating whether the value is present:
const hasValue = mySet.has(3); // true
To remove a value from the Set, use the delete method. This will remove the value if it exists, and return a boolean indicating whether the removal was successful:
const wasDeleted = mySet.delete(4); // true
If you want to iterate over the elements of a Set, you can use either a forEach loop or the for...of loop, both of which will give you access to each unique value:
mySet.forEach(value => {
console.log(value);
});
Alternatively, using for...of loops, you can achieve the same result:
for (const value of mySet) {
console.log(value);
}
Finally, if you want to clear all values from a Set at once, you can use the clear method. This will remove all entries and leave you with an empty Set:
mySet.clear();
console.log(mySet.size); // Outputs: 0