Creating a Set using Javascript

Web DevelopmentFront End TechnologyJavascript

Let's create a MySet class so that it doesn't hide the actual set class in JS. We'll create a container object that'll keep track of all our values that we add to the set. We'll also create a display function that prints the set for us. 

Example

class MySet {
   constructor() {
      this.container = {};
   }
   display() {
      console.log(this.container);
   }
}

In ES6, you can directly create a set using the Set class. For example, 

Example

const set1 = new Set();
const set2 = new Set([1, 2, 5, 6]);

Checking for membership

The has method checks if a value exists in the set or not. We'll use the Object.hasOwnProperty method to check it in the container. For example, 

Example

has(val) {
   return this.container.hasOwnProperty(val);
}

In ES6 Sets, you can use this directly − 

Example

const testSet = new Set([1, 2, 5, 6]);
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 15:38:34
Advertisements