Data Structures: Create a Set Class
This commit is contained in:
parent
5d990d9e6e
commit
3f3cf28667
41
Data Structures/setClass.js
Normal file
41
Data Structures/setClass.js
Normal file
@ -0,0 +1,41 @@
|
||||
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);
|
||||
}
|
||||
|
||||
// Only change code below this line
|
||||
add(item) {
|
||||
if (this.dictionary[item] === undefined) {
|
||||
this.dictionary[item] = true;
|
||||
this.length++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
remove(item) {
|
||||
if (this.dictionary[item] === undefined) {
|
||||
return false;
|
||||
}
|
||||
delete this.dictionary[item];
|
||||
this.length--;
|
||||
return true;
|
||||
}
|
||||
|
||||
size() {
|
||||
return this.length;
|
||||
}
|
||||
// Only change code above this line
|
||||
}
|
Loading…
Reference in New Issue
Block a user