# JavaScript数据结构——集合的实现与应用

class Set {
constructor () {
this.items = {};
}

if (!this.has(value)) {
this.items[value] = value;
return true;
}
return false;
}

delete (value) { // 从集合中删除对应的元素
if (this.has(value)) {
delete this.items[value];
return true;
}
return false;
}

has (value) { // 判断给定的元素在集合中是否存在
return this.items.hasOwnProperty(value);
}

clear() { // 清空集合内容
this.items = {};
}

size () { // 获取集合的长度
return Object.keys(this.items).length;
}

values () { // 返回集合中所有元素的内容
return Object.values(this.items);
}
}


let set = new Set();
console.log(set.values()); // [ 1 ]
console.log(set.has(1)); // true
console.log(set.size()); // 1

console.log(set.values()); // [ 1, 2 ]
console.log(set.has(2)); // true
console.log(set.size()); // 2

set.delete(1);
console.log(set.values()); // [ 2 ]

set.delete(2);
console.log(set.values()); // []


### 并集

union (otherSet) { // 并集
let unionSet = new Set();
return unionSet;
}


let setA = new Set();

let setB = new Set();

console.log(setA.union(setB).values()); // [ 'first', 'second', 'third', 'fourth', 'fifth', 'sixth' ]


### 交集

intersection (otherSet) { // 交集
let intersectionSet = new Set();
this.values().forEach(value => {
});
return intersectionSet;
}


let setA = new Set();

let setB = new Set();

console.log(setA.intersection(setB).values()); // [ 'second', 'third' ]


### 差集

difference (otherSet) { // 差集
let differenceSet = new Set();
this.values().forEach(value => {
});
return differenceSet;
}


let setA = new Set();

let setB = new Set();

console.log(setA.difference(setB).values()); // [ 'first' ]


### 子集

subset (otherSet) { // 子集
if (this.size() > otherSet.size()) return false;

let isSubset = true;
this.values().every(value => {
if (!otherSet.has(value)) {
isSubset = false;
return false;
}
return true;
});

return isSubset;
}


var arr = ["first", "second", "third", "fourth"];
arr.forEach(item => {
if(item === "third") return true;
console.log(item);
});


first
second
fourth


let setA = new Set();

let setB = new Set();

let setC = new Set();

console.log(setA.subset(setB)); // true
console.log(setA.subset(setC)); // false


let set = new Set();
console.log(set.values()); // [Set Iterator] { 1, 2, 3 }
console.log(set.has(1)); // true
console.log(set.size); // 2

set.delete(1);
console.log(set.values()); // [Set Iterator] { 2, 3 }

set.clear();
console.log(set.values()); // [Set Iterator] {  }