Sobes.tech
Middle

/* È necessario implementare il metodo intersection, che estende i metodi standard degli insiemi (Set). Il metodo prende un altro insieme come input e restituisce un nuovo insieme, che è l’intersezione dell’insieme originale e di quello passato, cioè, contiene solo gli elementi presenti in entrambi gli insiemi. */ // il tuo codice 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

Risposta dell'AI

Il metodo intersection per la classe Set può essere implementato aggiungendolo al prototipo Set. Prende un altro insieme e restituisce un nuovo insieme contenente solo gli elementi presenti in entrambi gli insiemi.

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

Questo metodo attraversa gli elementi del primo insieme e aggiunge al risultato solo quelli presenti nel secondo.