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 todictionary
. The method should returntrue
, if the value is successfully added to the dictionary and update the length property, otherwise it should returnfalse
. -
.remove()
method
This method should only remove values fromdictionary
. The method should returntrue
, if the value is successfully removed from the dictionary and update the length property, otherwise it should returnfalse
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;
}
}