集合
方法:
添加 是否含有某元素 删除等
并集 交集 差集 子集
function Set() {
this.items = {};
// add添加元素
Set.prototype.add = (value) => {
// 判断集合中是否已包含该元素
if (this.has(value)) return false;
this.items[value] = value;
return true;
};
// 判断集合中是否已包含该元素
Set.prototype.has = function(value) {
return this.items.hasOwnProperty(value);
};
// remove
Set.prototype.remove = (value) => {
if (!this.has(value)) return false;
delete this.items[value];
};
// clear
Set.prototype.clear = () => {
this.items = {};
};
// size
Set.prototype.size = function() {
return Object.keys(this.items).length;
};
// 读取集合中所有的键
Set.prototype.values =function () {
return Object.keys(this.items);
};
// 并集
Set.prototype.union = function (otherSet) {
var unionSet = new Set();
for (let value in this.items) {
unionSet.add(value);
}
for (let value in otherSet.items) {
unionSet.add(value);
}
return unionSet;
};
// 交集
Set.prototype.intersection = function (otherSet) {
var intersectionSet = new Set();
for (let value in this.items) {
if(otherSet.has(value)){
intersectionSet.add(value);
}
}
return intersectionSet;
};
// 差集
Set.prototype.difference = function (otherSet) {
var differenceSet = new Set();
for (let value in this.items) {
if (!otherSet.has(value)) {
differenceSet.add(value);
}
}
return differenceSet;
};
// 子集
Set.prototype.subset =function (otherSet) {
for (let value in this.items) {
if (!otherSet.has(value)) {
return false;
}
}
return true
};
}
测试
// test
var set = new Set();
set.add("first");
set.add("second");
set.add("second");
set.add("third");
set.add("abc");
console.log(set);
set.remove("first");
console.log(set);
console.log(set.size());
set.add("111");
console.log("set", set.values());
console.log(set.has("first"));
console.log(set.has("111"));
console.log("~~~~~~~~~~");
var setA = new Set();
setA.add("abc");
setA.add("first");
setA.add("new");
setA.add("111");
console.log("setA", setA.values());
var unionSet = set.union(setA);
console.log("unionSet", unionSet.values());
var jiao = set.intersection(setA);
console.log("intersection", jiao.values());
var difSet = set.difference(setA);
console.log(" difSet", difSet.values());
console.log('set',set.items);
console.log('setA',setA.items);
var sub=set.subset(setA)
console.log('sub',sub);
控制台输出