Add elements to a Set using Javascript

Web DevelopmentFront End TechnologyJavascript

The add method checks if a value already exists in the set, if not, then it adds that value to the set. We can implement it as follows − 

Example

add(val) {
   if (!this.has(val)) {
      this.container[val] = val; return true;
   }
   return false;
}

You can test this using − 

Example

const testSet = new MySet();

testSet.add(1);
testSet.add(2);
testSet.add(5);
testSet.add(2);

testSet.display();

console.log(testSet.has(5));
console.log(testSet.has(20));
console.log(testSet.has(1));

Output

This will give the output −

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

Note that even though we tried adding 2 twice, it only got added once. If you try logging it, you'll get a false. This is because of the values we're returning if we don't add it.

In ES6, you use the add function as follows −

Example

const testSet = new MySet();

testSet.add(1);
testSet.add(2);
testSet.add(5);
testSet.add(2);

console.log(testSet.has(5));
console.log(testSet.has(20));
console.log(testSet.has(1));

Output

This will give the output −

True
False
True
raja
Published on 27-Jun-2018 12:14:05
Advertisements