Set operations
We can perform the following operations on sets:
Union: Given two sets, this returns a new set with elements from both the given sets
Intersection: Given two sets, this returns a new set with the elements that exist in both sets
Difference: Given two sets, this returns a new set with all the elements that exist in the first set and do not exist in the second set
Subset: This confirms whether a given set is a subset of another set
Set union
The mathematic concept of union is: the union of sets A and B, denoted by:
This set is defined as:
This means that x (the element) exists in A or x exists in B. The following diagram exemplifies the union operation:
Now, let's implement the union
method in our Set
class via the following code:
this.union = function(otherSet){ let unionSet = new Set(); //{1} let values = this.values(); //{2} for (let i=0; i<values.length; i++){ unionSet.add(values[i]); } values = otherSet.values(); //{3} for (let i=0; i<...