js-实现集合的操作

function Set() {
var items = {};
this.has = function (value) {
return items.hasOwnProperty(value);
};
this.add = function (value) {//添加值
if (!this.has(value)) {
items[value]=value;
return false;
}
};
this.remove = function (value) {//删除某个值
if (this.has(value)) {
delete items[value];
return true;
}
return false;
};
this.clear = function () {//清除
items = {};
};
this.size = function () {
return Object.keys(items).length;
};
this.sizeLegacy = function () {//返回集合中有多少项
var count = 0;
for (var prop in items) {
if (items.hasOwnProperty(prop)) {
++count;
}
}
return count;
};
this.valueLegacy = function () {//输出现有值
var keys = [];
for (var key in items) {
keys.push(key);
}
return keys;
};
this.getItems = function () {
return items;
    };


    this.union = function (otherSet) {//合并集合
        var unionSet = new Set();


        var values = this.values();
        for (var i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }


        values = otherSet.values();
        for (var i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }


        return unionSet;
    };


    this.intersection = function (otherSet) {//交集
        var intersectionSet = new Set();


        var values = this.values();
        for (var i = 0; i < values.length; i++) {
            if (otherSet.has(values[i])) {
                intersectionSet.add(values[i]);
            }
        }


        return intersectionSet;
    };


    this.difference = function (otherSet) {//差集
        var differenceSet = new Set();
        var values = this.values();
        for (var i = 0; i < values.length; i++) {
            if (!otherSet.has(values[i])) {
                differenceSet.add(values[i]);
            }
        }


        return differenceSet;
    };


    this.subset = function (otherSet) {//子集


        if (this.size() > otherSet.size()) {
            return false;
        } else {
            var values = this.values();
            for (var i = 0; i < values.length; i++) {
                if (!otherSet.has(values[i])) {
                    return false;
                }
            }
            return true;
        }
    };


}
var set=new Set();
set.add(4);
console.log(set.valueLegacy());
console.log(set.has(1));
console.log(set.size());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值