freeCodeCamp Challenge Guide: Create a Set Class "modified"

Create a Set Class


The available hint is doesn’t match the given challenge

Problem Explanation

  • A Set is an abstract data structure.
  • It can store unique value and the collection is unordered.
  • In this challenge, we have to implement:
    • .add() method
      This method should only add unique values to dictionary. The method should return true, if the value is successfully added to the dictionary and update the length property, otherwise it should return false.
    • .remove() method
      This method should only remove values from dictionary. The method should return true, if the value is successfully removed from the dictionary and update the length property, otherwise it should return false if the element doesn’t exist.
    • .size() method
      This method should return the length property;

Solutions

Solution 1 (Click to Show/Hide)
class Set {
  constructor() {
    // Dictionary will hold the items of our set
    this.dictionary = {};
    this.length = 0;
  }

  // This method will check for the presence of an element and return true or false
  has(element) {
    return this.dictionary[element] !== undefined;
  }

  // This method will return all the values in the set
  values() {
    return Object.keys(this.dictionary);
  }

  // this method will add element to the set
  add(element){
    if(!this.has(element)){
        this.dictionary[element] = 0;
        this.length++;
        return true;
    }else{
      return false;
    }
  }
//this method will remove element from the set
  remove(element){
    if(this.has(element)){
      delete this.dictionary[element];
      this.length--;
      return true;
    }else{
      return false;
    }
  }
  //this will return the length of the set
  size(){
    return this.length;
  }
}

Relevant Links

it doesnot work in add it says you cannot add duplicate item in the function
and remove function it says you can only remove if it present
how can we solve pro