I think I have completed this correctly - but I cannot pass the tests. I’m obviously missing something but I have no idea any more what. My console.logs
appear to give me the result I am seeking - that is to say I create a set containing {'a', 'b', 'c'}
and then call the union method with ['c', 'd']
as the argument. The new set created returns - correctly I think - { dictionary: { a: 'a', b: 'b', c: 'c', d: 'd' }, length: 4 }
.
Any ideas?
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(setB) {
console.log(setB)
const newSet = new Set();
console.log(newSet)
this.values().forEach(value => newSet.add(value))
console.log(newSet)
if (setB.length) setB.forEach(value => newSet.add(value))
console.log(newSet)
return newSet
}
// Only change code above this line
}
And the way I have been calling it to test it works:
const obj = new Set()
obj.add('a')
obj.add('b')
obj.add('c')
obj.union(['c','d'])
Challenge: Perform a Union on Two Sets
Link to the challenge: