freeCodeCamp/Data Structures/setsUnion.js

63 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/perform-a-union-on-two-sets
class Set {
constructor() {
// This will hold the 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);
}
// This method will add an element to the set
add(element) {
if (!this.has(element)) {
this.dictionary[element] = element;
this.length++;
return true;
}
return false;
}
// This method will remove an element from a set
remove(element) {
if (this.has(element)) {
delete this.dictionary[element];
this.length--;
return true;
}
return false;
}
// This method will return the size of the set
size() {
return this.length;
}
// Only change code below this line
union(otherSet) {
const unionSet = new Set();
for (let set of [this, otherSet]) {
for (let key in set.dictionary) {
unionSet.add(key);
}
}
return unionSet;
}
// Only change code above this line
}
const setA = new Set();
for (let element of ["a", "b", "c"]) {
setA.add(element);
}
const setB = new Set();
setB.add("c");
setB.add("d");
console.log(setA.union(setB));