Hash Sets are collections of unique items i.e no element can be repeated.
Hash Sets were designed to give us a way of adding and looking for unique values in a collection in a quick manner.
The values in a Hash Set can be either simple primitives like strings or integers as well as more complex object types like object literals or arrays.
In TypeScript, as in JavaScript, the Hash Set is implemented as the Set object.
Creation:
To create a new empty Set, you use the following syntax:
let mySet = new Set();
Creating an empty Set takes O(1) time.
Constructing from iterable
The Set constructor also accepts an optional iterable object. If you pass an iterable object to the Set constructor, all the unique elements of the object will be added to the new set:
let elements = [1, '2', 'apple', 1];
let mySet = new Set(elements);
console.log(mySet); // Set(3) { 1, '2', 'apple' }
This takes O(n) time, where n is the number of elements in the iterable object.
Adding elements:
To add an element to the set, you use the add() method:
let mySet = new Set(['a', 'b', 'c']);
// Adding new elements:
mySet.add('d');
// Adding an existing element:
mySet.add('a'); // nothing happens
console.log(mySet); // Set(4) { 'a', 'b', 'c', 'd' }
The Set first checks if that element already exists and if so, it does nothing and also doesn't raise an error.
Adding an element to a Set takes O(1) time.
Checking if a value exists:
To check if a Set has a specific element, you use the has() method. The has() method returns true if the set contains the element, otherwise, it returns false.
let mySet = new Set(['a', 'b', 'c']);
let exist = mySet.has('a');
console.log(exist); // true
exist = mySet.has('z');
console.log(exist); // false
Checking if a value exists in a Set takes O(1) time.
Removing elements:
To delete a specified element from a set, you use the delete() method:
let mySet = new Set(['a', 'b', 'c', 'd']);
// Deleting elements:
mySet.delete('a');
// Deleting a non-existent element:
mySet.delete('z'); // does nothing
console.log(mySet); // Set(3) { 'b', 'c', 'd' }
The Set first checks if that element exists and if not, it does nothing and also doesn't raise an error, so it's safe to delete non-existing elements.
Removing an element from a Set takes O(1) time.
Iterating over the Set values:
If we want to iterate over values of the Set, we can use the for loop along with the of operator:
let mySet = new Set(['b', 'c', 'c', 'd']);
for (let val of mySet) {
console.log(val);
}
// This will print the following:
// b
// c
// d
Iterating over a Set takes O(n) time.
Space Complexity
A Set uses O(n) space, where n is the number of elements existing in the Set.
Assignment
Follow the Coding Tutorial and let's play with some Hash Sets.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
