The add method

The next method we will implement is the add method, as follows:

add(element) {  if (!this.has(element)) {    this.items[element] = element; // {1}    return true;  }  return false;} 

Given an element, we can check whether the element already exists in the set. If not, we add the element to the set ({1}) and return true to indicate that the element was added. If the element already exists in the set, we simply return false to indicate that the element was not added.

We are adding the element as the key and value because it will help us search for the element if we store it as the key as well.

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.