Adding two Sets in Javascript

Web DevelopmentJavascriptFront End Technology

The operation of adding 2 sets is known as a union. You need to add every object from one set to another while checking for duplicates. We can just use the 2 methods we already implemented to implement this method.

We'll implement this function as a static function as we don’t want to mutate existing sets, but create and return a new one. We first need to check if the object passed to it is really an instance of the MySet class. 

Example

static union(s1, s2) {
   if (!s1 instanceof MySet || !s2 instanceof MySet) {
      console.log("The given objects are not of type MySet");
      return null;
   }
   let newSet = new MySet();
   s1.forEach(elem => newSet.add(elem));
   s2.forEach(elem => newSet.add(elem));
   newSet;
}

You can test this using − 

Example

const testSet1 = new MySet();
testSet1.add(1);
testSet1.add(2);

const testSet2 = new MySet();
testSet2.add(2);
testSet2.add(5);

let testSet3 = MySet.union(testSet1, testSet2);
testSet3.display();

Output

This will give the output −

{ '1': '1', '2': '2', '5': '5' }

Note that the union function is not there in the ES6 API as well. You can make this function be available in the Set class as follows &minusl 

Example

Set.union = function(s1, s2) {
   if (!s1 instanceof Set || !s2 instanceof Set) {
      console.log("The given objects are not of type Set");
      return null;
   }
   let newSet = new Set();
   s1.forEach(elem => newSet.add(elem));
   s2.forEach(elem => newSet.add(elem));
   return newSet;
}

You can test this using −

Example

let setA = new Set([1, 2, 3, 4]);
let setB = new Set([2, 3]);
console.log(Set.union(setA, setB));

Output

This will give the output −

Set { 1, 2, 3, 4 }
raja
Published on 27-Jun-2018 16:18:30
Advertisements