js实现集合方法

function Set(){
var items = new Object();
this.has = function (value) {
//两种方式都可以
//return value in items;
return items.hasOwnProperty(value);
};
this.add = function(value){
if(!this.has(value)){
items[value] = value;
return true;
}
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.values = function () {
return Object.keys(items);
};
this.valuesLegacy = function(){
var keys=[];
for(var key in items){
keys.push(key);
}
return keys;

};

//并集
this.union = function(otherSet){
var unionset = new Set();
var values = this.values();
for(var i=0;i<values.length;i++){
unionset.add(values[i]);
};
var values = otherSet.values();
for(var i=0;i<values.length;i++){
unionset.add(values[i]);
}
return unionset;
}


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


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


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

}


var set = new Set();
set.add("hello");
set.add("world");
console.log(set.values());

console.log(set.size());


//并集使用例子
var set1 = new Set();
set1.add("aa");
set1.add("bb");
set1.add("cc");

var set2 = new Set();
set2.add("aa");
set2.add("bbb");
set2.add("cc");

var union12 = set1.union(set2);
console.log(union12.values());//可以把重复的给删除


//交集使用例子
var set11 = new Set();
set11.add("aa");
set11.add("bb");
set11.add("cc");

var set22 = new Set();
set22.add("aa");
set22.add("bbb");
set22.add("cc");

var union1122 = set11.intersection(set22);
console.log(union1122.values());


//差集使用例子
var setc = new Set();
setc.add("aa");
setc.add("bb");
setc.add("cc");

var setd = new Set();
setd.add("aa");
setd.add("bbb");
setd.add("cc");

var unioncd = setc.different(setd);//这个注意调用顺序
console.log(unioncd.values());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值