js实现集合方法

来源:互联网 发布:设计模式 php 编辑:程序博客网 时间:2024/06/07 14:06
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());

原创粉丝点击