Perform a Union on Two Sets

Perform a Union on Two Sets
0.0 0

#1

My union function is not pass , it print error final.indexOf is not a function !!!

Your code so far


function Set() {
    // the var collection will hold the set
    var collection = [];
    // this method will check for the presence of an element and return true or false
    this.has = function(element) {
        return (collection.indexOf(element) !== -1);
    };
    // this method will return all the values in the set
    this.values = function() {
        return collection;
    };
    // this method will add an element to the set
    this.add = function(element) {
        if(!this.has(element)){
            collection.push(element);
            return true;
        }
        return false;
    };
   // this method will remove an element from a set
    this.remove = function(element) {
        if(this.has(element)){
           var index = collection.indexOf(element);
            collection.splice(index,1);
            return true;
        }
        return false;
    };
    // this method will return the size of the set
    this.size = function() {
        return collection.length;
    };
    // change code below this line
    this.union = function(arr) {
        for(var i = 0; i < arr.length; i++) {
            if(!this.has(arr[i])) {
                this.add(arr[i]);
            }
        }
        return this.values();
    }
    // change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/perform-a-union-on-two-sets/


#2

Hi,
I’m not seeing it in your code but that means somewhere you have called .indexOf on a variable named final except final is not an array. Do you have a variable ‘final’?


#3

That’a all my code ! I never use final variable . Could it be a bug of question ?


#4

Duh - I missed some things.

You are returning this.values() . The test is expecting you to return a Set object, not an array. this.values() returns an array.

Also, your function is based on an array parameter. The value actually passed to your function is also a Set, not an array.