The has(element) method

The first method we will implement is the has(element) method. We will implement this method first because it will be used in other methods, such as add and remove, to verify whether the element already exists in the set. We can take a look at its implementation here:

has(element){ 
  return element in items; 
}; 

Since we are using an object to store all the elements of the set, we can use JavaScript's in operator to verify that the given element is a property of the items object.

However, there is a better way of implementing this method, which is as follows:

has(element) {  return Object.prototype.hasOwnProperty.call(this.items, element);}

The Object prototype has the hasOwnProperty method. This method returns a boolean ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.