Union of 2 sets (interview prep)

just wondering if anyone else thinks this is a test-suite gremlin, or am i missing something.
it’s all at the bottom of the code in the union() method and after, (i only added the print() method to the given code elsewhere).
the outputs look fine but it’s not passing, at all.

class Set {
constructor() {
  // This will hold the set
  this.dictionary = {};
  this.length = 0;
}
print(){
  console.log(this.dictionary)
}
// 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;
}
union(setB){
  let setValsA = Object.values(this.dictionary)
  let setValsB = Object.values(setB.dictionary)
  console.log('setValsA:',setValsA, 'setValsB:',setValsB)
  return setValsA.concat(setValsB.filter((item) => setValsA.indexOf(item) < 0))
}
}
let setA = new Set()
setA.add('a');setA.add('b');setA.add('c')
setA.print()
let setB = new Set()
setB.add('c');setB.add('d')
setB.print()
console.log('result:',
setA.union(setB)
)
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36

Challenge: Perform a Union on Two Sets

Link to the challenge:

You’re including everything in set A, even if it’s not in set B

Also, you are not creating another set.

1 Like

right, i’m going to bed.
thanks.

actually i thought that was what i was supposed to be doing.
but it’s hard to know as it’s past bed time and i’ll look in the morning

Woops, that part I was mistaken about. You have an array though instead of a set. You must return a set.

lol, i fixed it with some hideous looking code:

  union(setB){
    let setValsA = Object.values(this.dictionary)
    let setValsB = Object.values(setB.dictionary)
    console.log('setValsA:',setValsA, 'setValsB:',setValsB)
    let newVals = setValsA.concat(setValsB.filter((item) => setValsA.indexOf(item) < 0))
    let newSet = new Set()
    for(let i in newVals){
      console.log(newVals[i])
        newSet.add(newVals[i])
    }
    console.log('newSet:',newSet)
    return newSet
  }

thank you, i’ll take a look into a tidy up tomorrow, g’night

One way to clean up is to use the fact that sets don’t create duplicate elements internally.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.