JavaScript实现集合

function set(){
this.dataStore=[];
this.add=add;
this.remove.remove;
this.size=size;
this.union=union;
this.intersect=intersect;
this.subset=subset;
this.difference=difference;
this.show=show;

}

function add(data){
if(this.dataStore.indexOf(data)<0){//集合的唯一性
this.dataSource.push(data);
}
else{
return false;
}
}

function remove(data){
var pos=this.dataStore.indexOf(data);
if(pos>-1)
{
this.dataStore.splice(pos,1);
}

else
{
return false;
}
}


function show(){
return this.dataStore;

}


function union(set)
{
var tempset=new set;
for(var i=0;i<this.dataStore.length;i++)
{
tempset.add(this.dataStore[i]);
}

for(var i=0;i<set.dataStore.length;++i)
{
if(!tempset.contains(set.dataStore[i]))
{
tempset.dataStore.push(set.dataStore[i]);

}
}

return tempset;

}


function intersect(set)
{
var tempset=new set();
for(var i=0;i<this.dataStore.length;i++)
{
if(set.contains(this.dataStore[i])){
tempset.add(set.dataStore[i]);

}
}

return tempset;
}


function subset(set){
if(this.size()>set.size()){
return false;
}

else{
for(var key in this.dataStore)
{

if(!set.contains(key)){
return false;
}

}

}

return true;

}


function size(){
return this.dataStore.length;

}


function difference(set)
{

var tem,pset=new set();

for(var key in this.dataStore)
{
if(!set.contains(key))
{
tempset.add(key);
}

}

return tempset;

}

原文地址:https://www.cnblogs.com/aobama/p/4347001.html