Learning JavaScript Data Structures and Algorithms by Loiane Groner

Learning JavaScript Data Structures and Algorithms by Loiane Groner

Author:Loiane Groner
Language: eng
Format: mobi, epub, pdf
Publisher: Packt Publishing
Published: 2014-10-26T22:00:00+00:00


var values = this.values();

for (var i=0; i<values.length; i++){ //{2}

if (otherSet.has(values[i])){ //{3}

intersectionSet.add(values[i]); //{4}

}

}

return intersectionSet;

}

For the intersection method, we need to find all elements from the current instance of the Set class that also exist in the given Set instance. So first, we create a new Set instance so that we can return it with the common elements (line {1}). Next, we iterate through all the values of the current instance of the Set class (line {2}) and we verify that the value exists in the otherSet instance as well (line {3}). We can use the has method that we implemented earlier in this chapter to verify that the element exists in the Set instance. Then, if the value exists in the other Set instance also, we add it to the created intersectionSet variable (line {4}) and return it.

Let's do some testing:

var setA = new Set();

setA.add(1);

setA.add(2);

setA.add(3);



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.