Tell us what’s happening:
My solution appears to return the proper values for the intersection set however it’s not passing the second test.
I’ve tried changing variables names, and also per the previous ‘union set’ example, I’m returning a new set for this method too.
I’ve tried a few different inputs and all seem to return the proper ‘intersection values’.
Edit: Solved this by remove ‘values’ method from the return statement
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 collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new Set();
var firstSet = this.values();
var secondSet = otherSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
});
secondSet.forEach(function(e){
unionSet.add(e);
});
return unionSet;
};
// change code below this line
this.intersection = function(otherSet) {
let intersectionSet = new Set()
let firstSet = this.values()
let secondSet = otherSet.values()
console.log('size a', firstSet.length, firstSet)
console.log('size b', secondSet.length, secondSet)
for (let i = 0; i < firstSet.length; i++) {
console.log('has i',i, firstSet[i], this.has(firstSet[i]))
if(otherSet.has(firstSet[i])) {
//let index = secondSet.indexOf(firstSet[i])
intersectionSet.add(firstSet[i])
}
}
for (let j = 0; j < secondSet.length; j++) {
console.log('has j', j, secondSet[j], this.has(secondSet[j]))
if(this.has(secondSet[j])) {
//let index = firstSet.indexOf(secondSet[j])
intersectionSet.add(secondSet[j])
}
}
console.log('inside', intersectionSet.values())
return intersectionSet.values()
}
// change code above this line
}
let setA = new Set()
setA.add('a')
setA.add('b')
setA.add('c')
setA.add('e')
setA.add('g')
//console.log('values a', setA.values())
let setB = new Set()
setB.add('a')
setB.add('b')
setB.add('d')
setB.add('e')
//console.log('values b', setB.values())
//console.log('return', setA.intersection(setB))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
.
Challenge: Perform an Intersection on Two Sets of Data
Link to the challenge: