#Data Structure - Set @(Data Structure & Algorithm)
function Set(){
this.dataStore = [];
}
Set.prototype = {
constructor: Set,
add: function(el){
if (this.dataStore.indexOf(el) > -1){
return false;
} else{
this.dataStore.push(el);
return true;
}
},
remove: function(el){
var index = this.dataStore.indexOf(el);
if (index < 0)
return false;
else{
this.dataStore.splice(index, 1);
return true;
}
},
getSize: function(){
return this.dataStore.length;
},
contains: function(el){
if (this.dataStore.indexOf(el) > -1){
return true;
} else
return false;
},
union: function(set){
var r = new Set(),
el;
//这里必须深复制!!
for (var i = 0; i < this.getSize(); i++){
r.add(this.dataStore[i]);
}
for (i = 0; i < set.getSize(); i++){
el = set.dataStore[i];
if (!r.contains(el)){
r.add(el);
}
}
return r;
},
intersect: function(set){
var r = new Set(),
el;
for (var i = 0; i < set.getSize(); i++){
el = set.dataStore[i];
if (this.contains(el)){
r.add(el);
}
}
return r;
},
isSubsetOf: function(set){
var el,
i = 0;
if (this.getSize() > set.getSize())
return false;
while (set.contains(this.dataStore[i])){
i++;
}
if (i === this.getSize()){
return true;
}
else
return false;
},
//return els belong to this, but not to set
complementOf: function(set){
var r = new Set(),
el;
for (var i = 0; i < this.getSize(); i++){
el = this.dataStore[i];
if (!set.contains(el)){
r.add(el);
}
}
return r;
},
display: function(){
for (var i = 0; i < this.getSize(); i++){
console.log(this.dataStore[i]);
}
}
};