Sobes.tech
Middle

/* Standart to'plam metodlarini kengaytiradigan intersection metodini amalga oshirish kerak. Ushbu metod boshqa to'plamni qabul qiladi va yangi to'plamni qaytaradi, bu asl to'plam va uzatilgan to'plamning kesishmasi, ya'ni, faqat ikkala to'plamda mavjud bo'lgan elementlarni o'z ichiga oladi. */ // kodingiz 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

AIdan javob

Set sinfi uchun intersection usuli uni Set prototipiga qo'shish orqali amalga oshirilishi mumkin. U boshqa to'plamni qabul qiladi va faqat ikkala to'plamda mavjud bo'lgan elementlarni o'z ichiga olgan yangi to'plamni qaytaradi.

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

Bu usul birinchi to'plam elementlarini aylanib chiqadi va faqat ikkinchi to'plamda mavjud bo'lganlarni natijaga qo'shadi.