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.values(this.dictionary);
}
// Only change code below this line
// This method will add element to the set
add(element) {
if (!this.has(element)) {
this.dictionary[element] = element;
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;
}
// Only change code above this line
}