JavaScript数据结构与算法(六):集合

/**
 * JavaScript的对象不允许一个键指向两个不同的属性
 * 这一点保证了集合中的元素都是唯一的
 */ 
function Set() {  
    var items = {};
    var length = 0;
    this.add = function (val) {  
        if(!this.has(val)) {
            items[val] = val;
            length++;
            return true;
        }
        return false;
    }
    this.has = function (val) {  
        return items.hasOwnProperty(val);
    }
    this.remove = function (val) {  
        if(this.has(val)) {
            delete items[val];
            length--;
            return true;
        }
        return false;
    }
    this.clear = function () {  
        items = {};
        length = 0;
    }
    this.size = function () {  
        return length;
    }
    /**
     * 只能在现代浏览器中运行
     * e.g.:IE9, Firefox 4.0+, Chrome 5.0+,Opera 12.0+,Safari 5.0+
     * Object.keys返回一个属性的数组
     */
    this.size = function () {  
        return Object.keys(items).length;
    } 
    /**
     * 这种实现方法可以在任何浏览器上运行
     */ 
    this.size = function () {  
        var count = 0;
        for(var prop in items) {
            if(items.hasOwnProperty(prop))
                ++count;
        }
        return count;
    }
    this.print = function () {  
        for(var prop in items) {
            console.log(items[prop]);
        }
    }
    this.values = function () {  
        return Object.keys(items);
    }
    // 集合操作

    /**
     * 
     * @param set 右操作数
     * @return 并集 
     */ 
    this.union = function (set) {  
        var unionSet = new Set();
        var values = this.values();
        values.forEach(element => {
            unionSet.add(element);
        });
        values = set.values();
        values.forEach(ele => {
            unionSet.add(ele);
        });
        return unionSet;
    }
    /**
     * 
     * @param set
     * @return 交集
     */ 
    this.intersection = function (set) {  
        var intersectionSet = new Set();
        var values = this.values();
        values.forEach( ele => {
            if(set.has(ele)) {
                intersectionSet.add(ele);
            }
        });
        return intersectionSet;
    }
}

module.exports = Set;

猜你喜欢

转载自blog.csdn.net/w_bu_neng_ku/article/details/80623563