Middle
/* On vaja implementerida meetod intersection, mis laiendab standardseid kogude (Set) meetodeid. See meetod võtab sisendiks teise kogumi ja tagastab uue kogumi, mis on algse ja antud kogumi lõike, tähendab, sisaldab ainult neid elemente, mis on mõlemas kogumis. */ // sinu kood 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
Vastus AI-lt
Set klassi intersection meetodit saab rakstīt, pievienojot to Set prototipam. Tas pieņem citu kopu un atgriež jaunu kopu, kas satur tikai tos elementus, kas ir abās kopās.
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
Šī metode pārbauda pirmā kopas elementus un pievieno rezultātam tikai tos, kas ir arī otrajā kopā.