Sobes.tech
Middle

/* Implement the intersection method that extends the standard Set methods. The method takes another set as input and returns a new set that is the intersection of the original and the passed sets, containing only elements present in both sets. */ // your code const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([3, 4, 5, 6, 7, 8]); console.log(...set1.intersection(set2)) // 3 4 --- Set.prototype.intersection = function (set2) { const result = new Set(); for(const value of this) { if (set2.has(value)) result.add(value); } return result; } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([3, 4, 5, 6, 7, 8]); console.log(...set1.intersection(set2)) // 3 4

sobes.tech AI

Answer from AI

The intersection method for the Set class can be implemented by adding it to the Set prototype. It takes another set and returns a new set containing only the elements that are present in both sets.

Set.prototype.intersection = function (otherSet) {
    const result = new Set();
    for (const item of this) {
        if (otherSet.has(item)) {
            result.add(item);
        }
    }
    return result;
};

const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([3, 4, 5, 6, 7, 8]);

console.log(...set1.intersection(set2)); // 3 4

This method iterates over the elements of the first set and adds to the result only those that are present in the second.