第四章、集合
集合是有一组无序且唯一的项组成的。
构建数据集合
class Set {
constructor() {
// 使用对象来实现集合
this.items = {};
}
// 判断元素是否存在于集合
has(item) {
return Object.prototype.hasOwnProperty.call(this.items, item);
}
// 添加元素
add(item) {
if (!this.has(item)) {
this.items[item] = item;
return this.values();
}
return false;
}
// 删除元素
delete(item) {
if (this.has(item)) {
const delItem = this.items[item];
delete this.items[item];
return delItem;
}
return undefined;
}
// 清空元素
clear() {
this.items = {};
}
// 集合大小
size() {
return Object.keys(this.items).length;
}
// 返回集合
values() {
return Object.values(this.items);
}
// 求并集
union(otherSet) {
const unionSet = new Set();
this.values().forEach(item => unionSet.add(item));
otherSet.values().forEach(item => unionSet.add(item));
return unionSet;
}
// 求交集
interSection(otherSet) {
const interSet = new Set();
const values = this.values();
const otherValues = otherSet.values();
let bigSet = values;
let smallSet = otherValues;
if (otherValues.length > values.length) {
bigSet = otherValues;
smallSet = values;
}
smallSet.forEach(item => {
if (bigSet.includes(item)) {
interSet.add(item);
}
});
return interSet;
}
// 求差集
difference(otherSet) {
const differenceSet = new Set();
this.values().forEach(item => {
if (!otherSet.has(item)) {
differenceSet.add(item);
}
});
return differenceSet;
}
// 是否为子集
isSubSet(otherSet) {
if (this.size > otherSet.size()) {
return false;
}
return this.values().every(item => {
if (!otherSet.has(item)) {
return false;
}
return true;
});
}
}
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
80
81
82
83
84
85
86
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
80
81
82
83
84
85
86
ECMAScript 2015的Set类
ECMAScript 2015新增了Set类。
const a = new Set();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
const b = new Set();
b.add(3);
b.add(4);
b.add(5);
b.add(6);
// values方法返回Iterator遍历接口
console.log(a.values());
// delete方法按值删除元素,删除成功返回true,失败返回false
console.log(b.delete(3));
// 求并集
function union(setA, setB) {
return new Set([...setA, ...setB]);
}
// 求交集
function interSection(setA, setB) {
return new Set([...setA].filter(item => setB.has(item)));
}
// 求差集
function difference(setA, setB) {
return new Set([...setA].filter(item => !setB.has(item)));
}
// 是否为子集
function isSubSet(setA, setB) {
return [...setA].every(item => setB.has(item))
}
console.log(union(a,b));
console.log(interSection(a,b));
console.log(difference(a,b));
console.log(isSubSet(a,b));
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
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