# 集合

❑ add (element):向集合添加一个新元素。
❑ delete (element):从集合移除一个元素。
❑ has (element):如果元素在集合中,返回 true,否则返回 false。
❑ clear ():移除集合中的所有元素。
❑ size ():返回集合所包含元素的数量。它与数组的 length 属性类似。
❑ values ():返回一个包含集合中所有值(元素)的数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Set集合  JS在ES2015加入了 Set 和 Map
/*
❑ add(element):向集合添加一个新元素。
❑ delete(element):从集合移除一个元素。
❑ has(element):如果元素在集合中,返回true,否则返回false。
❑ clear():移除集合中的所有元素。
❑ size():返回集合所包含元素的数量。它与数组的length属性类似。
❑ values():返回一个包含集合中所有值(元素)的数组。
*/

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

add(element){
if(this.has(element)) return false
this.items[element]=element
return true
}

delete(element){
try{
delete this.items[element]
return true
}catch{
return false
}
}

has(element){
// return element in this.items 以下更好
return Object.prototype.hasOwnProperty.call(this.items, element);
}

clear(){
this.items={}
return true
}

size(){
// return Object.keys(this.items).length 这个太简单了
let count = 0;
for(let key in this.items) { // {2}
if(this.items.hasOwnProperty(key)) { // {3}
count++; // {4}
}
return count;
}
}

values(){
// return Object.values(this.items) 这个也是
let values = [];
for(let key in this.items) { // {1}
if(this.items.hasOwnProperty(key)) {
values.push(key); // {2}
}
}
return values;
}
}

// 集合运算
/*
❑ 并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合。
❑ 交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合。
❑ 差集:对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集合的元素的新集合。
❑ 子集:验证一个给定集合是否是另一集合的子集。
*/



// console.log(set.add(1))
// console.log(set.add(3))
// console.log(set.add('a'))
// console.log(set.has(3))
// console.log(set.size())
// console.log(set.values())