Sobes.tech
Middle

/* Standart to'plam metodlarini kengaytiradigan intersection metodini amalga oshirish kerak. Ushbu metod boshqa bir to'plamni qabul qiladi va yangi to'plamni qaytaradi, bu, asl to'plam va uzatilgan to'plamning kesishmasidir, yani, 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

AIден жооп

Set классынын intersection ыкмасы Set прототипуна кошулуп ишке ашырылышы мүмкүн. Ал башка топтомду кабыл алып, эки топтомдо да бар элементтерди камтыган жаңы топтомду кайтарат.

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

Бул ыкма биринчи топтомдун элементтерин өтүп, экинчи топтомдо барларды гана кошот.