使用javaScript实现集合

class Set{
    constructor(){
        this.items = {};
    }
    has(element){
       return Object.prototype.hasOwnProperty.call(this.items,element);
    }
    add(element){
        if(!this.has(element)){
            this.items[element] = element;
            return true;
        }
        return false;
    }
    delete(element){
        if(this.has(element)){
            delete this.items[element];
            return true;
        }
        return false;
    }
    clear(){
        this.items = {};
    }
    size(){
        return Object.keys(this.items).length;//ES6
    }
    values(){
        let values = [];
        for(let key in this.items){
            if(this.items.hasOwnProperty(key)){
                values.push(key);
            }
        }
        return values;
    }
    //并集
    union(otherSet){
        const unionSet = new Set();
        this.values().forEach(value=>unionSet.add(value));
        otherSet.values().forEach(value => unionSet.add(value));
        return unionSet;
    }
    //交集
    intersection(otherSet){
        const intersection = new Set();
        let biggerSet = this.values();
        let smallerSet = otherSet.values();
        if(biggerSet.length < smallerSet.length){
            biggerSet = otherSet.values();
            smallerSet = this.values();
        }
        smallerSet.forEach(value=>{
            if(biggerSet.includes(value)){
                intersection.add(value);
            }
        });
        return intersection;
    }
    //差集
    difference(otherSet){
        const differenceSet = new Set();
        this.values.forEach(value=>{
            if(!otherSet.includes(value)){
                differenceSet.add(value);
            }
        });
        return differenceSet;
    }
    //子集
    isSubsetOf(otherSet){
        if(this.values.length<otherSet.length){
            return false;
        }
        let isSubset = true;
        otherSet.values().every(value=>{
            if(!this.values().includes(value)){
                isSubset = false;
                return false;
            }
            return true;
        });
        return isSubset;
    }
}
原文地址:https://www.cnblogs.com/MySweetheart/p/13223764.html