JavaScript中自带Set集合类及模拟实现并集交集差集

let set = new Set();

function union(set1, set2) {   //set1与set2的并集
    let unionSet = new Set();
    set1.forEach(element => {
        unionSet.add(element);
    });
    set2.forEach(element => {
        unionSet.add(element);
    });

    return unionSet;
}

function intersection(set1, set2) {   //set1与set2的交集
    let intersectionSet = new Set();
    if (set1.size <= set2.size) {
        set1.forEach(x => {
            if (set2.has(x)) {
                intersectionSet.add(x);
            }
        });
    } else {
        set2.forEach(x => {
            if (set1.has(x)) {
                intersectionSet.add(x);
            }
        });
    }
    return intersectionSet;
}

function difference(set1, set2) {   //set1-set2 差集
    let differenceSet = new Set();
    set1.forEach(x => {
        if (set2.has(x)) {
            differenceSet.add(x);
        }
    });
    return differenceSet;
}


//测试用例
set.add(1);
console.log(set.values()); // outputs @Iterator
console.log(set.has(1)); // outputs true
console.log(set.size); // outputs 1

set.add(2);
console.log(set.values()); // outputs [1, 2]
console.log(set.has(2)); // true
console.log(set.size); // 2

set.delete(1);
console.log(set.values()); // outputs [2]

set.delete(2);
console.log(set.values()); // outputs []

const setA = new Set();
setA.add(1);
setA.add(2);
setA.add(3);

const setB = new Set();
setB.add(2);
setB.add(3);
setB.add(4);

console.log(union(setA, setB));

console.log(new Set([...setA, ...setB]));

console.log(intersection(setA, setB));

console.log(new Set([...setA].filter(x => setB.has(x))));

console.log(difference(setA, setB));

console.log(new Set([...setA].filter(x => !setB.has(x))));

 

上一篇:test


下一篇:如何合并HashSet?