首页 > 编程语言 > 详细

使用javaScript实现集合

时间:2020-07-02 12:45:09      阅读:60      评论:0      收藏:0      [点我收藏+]
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;
    }
}

 

使用javaScript实现集合

原文:https://www.cnblogs.com/MySweetheart/p/13223764.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!