11. JavaScript数据结构之集合及集合操作

119 阅读1分钟

集合

集合封装

function Set() {
    this.items = {}
    // 添加一个新的项
    Set.prototype.add = function (value) {
        if (this.has(value)) {
            return false;
        }
        this.items[value] = value;
        return true;
    }
    // 移除
    Set.prototype.remove = function (value) {
        if (!this.has(value)) {
            return false;
        }
        delete this.items[value];
        return true;
    }
    // 是否在集合中
    Set.prototype.has = function (value) {
        return this.items.hasOwnProperty(value)
    }
    // 清空
    Set.prototype.clear = function () {
        this.items = {}
    }
    // 返回元素数量
    Set.prototype.size = function () {
        return Object.keys(this.items).length
    }
    // 返回一个包含集合中所有值的数组
    Set.prototype.values = function () {
        return Object.keys(this.items)
    }
}

集合操作

并集

创建一个新集合,遍历两个集合,加入新集合中

Set.prototype.union = function (otherSet) {
    var unionSet = new Set();
    var values = this.values();

    for (let index = 0; index < values.length; index++) {
        unionSet.add(values[index])
    }

    values = otherSet.values();
    for (let index = 0; index < values.length; index++) {
        unionSet.add(values[index])
    }
    return unionSet
}

交集

创建一个新集合,遍历集合1中元素,判断是否在集合二中,是则添加到新集合,最后返回新集合

Set.prototype.intersection = function (otherSet) {
    var unionSet = new Set();
    var values = this.values();
    for (let index = 0; index < values.length; index++) {
        var item = values[index];
        if (otherSet.has(item)) {
            unionSet.add(values[index]);
        }
    }
    return unionSet;
}

差集

创建一个新集合,遍历集合1中元素,判断是否在集合二中,否则添加到新集合,最后返回新集合

Set.prototype.difference = function (otherSet) {
    var unionSet = new Set();
    var values = this.values();
    for (let index = 0; index < values.length; index++) {
        var item = values[index];
        if (!otherSet.has(item)) {
            unionSet.add(values[index]);
        }
    }
    return unionSet;
}

子集

判断一个集合是不是另一个集合的子集

1.判断集合1长度是否大于集合2

2.不大于的情况

判断集合1中的元素是否在集合2中,是则为子集

Set.prototype.subset = function (otherSet) {
    if (this.size() < otherSet.size()) {
        return false;
    }
    var values = this.values();
    for (let index = 0; index < values.length; index++) {
        var item = values[index];
        if (!otherSet.has(item)) {
            return false;
        }
    }
    return true;
}