集合
function Set() {
let items = {}; //用对象,因为一个键不能指向两个值,保证唯一性
this.has = function(value) {
return value in items;
};
//has更好的方式
this.has = function(value) {
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.values = function() {
let values = [];
for(let i = 0, keys = Object.keys(items); i < keys.length; i++){
value.push(items[keys[i]]);
}
return values;
};
}
集合操作
并集
首先创建一个新的集合,代表两个集合的并集。然后获取第一个集合(当前Set类实例)所有的值,遍历并全部添加到代表并集的集合中,然后对第二个集合做同样的事。最后返回结果。
this.union = function(otherSet) {
let unionSet = new Set();
let values = this.values();
for(let i = 0; i<values.length; i++) {
unionSet.add(values[i]);
}
values = otherSet.values();
for(let i = 0; i<values.length; i++) {
unionSet.add(values[i]);
}
return unionSet;
};
交集
首先创建一个新的Set实例,这样就能用它返回共有的元素。接下来遍历当前Set实例所有的值,验证它们是否也存在于otherSet实例,然后如果这个值也存在于另一个Set实例中,就将其添加到创建的intersectionSet变量中。
this.intersection = function(otherSet){
let intersectionSet = new Set();
let values = this.values();
for(let i = 0; i<values.length; i++) {
if(otherSet.has(values[i])){
intersectionSet.add(values[i]);
}
}
return intersectionSet
}
差集
this.difference = function(otherSet){
let differenceSet = new Set();
let values = this.values();
for(let i = 0; i<values.length; i++) {
if(!otherSet.has(values[i])){
difference.add(values[i]);
}
}
return differenceSet;
}
子集
当前实例中的元素比otherSet实例更多,他就不是一个子集。然后遍历集合中所有元素,验证这些元素也存在于otherSet中。
this.subset = function(otherSet){
if(this.size() > otherSet.size()){
return false;
} else {
let values = this.values();
for(let i = 0; i<values.length; i++) {
if(!otherSet.has(values[i])){
return false;
}
}
return true;
}
};