集合

集合

集合是由一种无序唯一(即不能重复)的项组成的。

Set类的模拟实现

虽然ES2015给我们提供了原生的Set类,但是并没有实现并集、交集、差集、子集等数学运算,这里我们模拟实现自己的Set类。

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
class Set {
// 构造函数
constructor() {
this.items = {};
}
// 如果元素在集合中,返回true,否则返回false
has(element) {
return element in this.items;
}
// 向集合添加一个元素
add(element) {
if (!this.has(element)) {
this.items[element] = element;
return true;
}
return false;
}
// 从集合移除一个元素
delete(element) {
if (this.has(element)) {
delete this.items[element];
return true;
}
return false;
}
// 移除集合中的所有元素
clear() {
this.items = {};
}
// 返回集合所包含元素的数量。它与数组的length属性类似
size() {
return Object.keys(this.items).length;
}
// 返回一个包含集合中所有值(元素)的数组
values() {
return Object.values(this.items);
}
// 并集
union(otherSet) {
const unionSet = new Set();
this.values().forEach(value => {
unionSet.add(value);
});
otherSet.values().forEach(value => {
unionSet.add(value);
});
return unionSet;
}
// 交集
intersection(otherSet) {
const intersectionSet = new Set();
const values = this.values();
for (let i = 0; i < values.length; i++) {
if (otherSet.has(values[i])) {
intersectionSet.add(values[i]);
}
}
return intersectionSet;
}
// 改进版交集
intersectionPlus(otherSet) {
const intersectionSet = new Set();
const values = this.values();
const otherValues = otherSet.values();
let biggerSet = values;
let smallerSet = otherValues;
if (otherValues.length - values.length > 0) {
biggerSet = otherValues;
smallerSet = values;
}
smallerSet.forEach(value => {
if (biggerSet.includes(value)) {
intersectionSet.add(value);
}
});
return intersectionSet;
}
// 差集
difference(otherSet) {
const differenceSet = new Set();
this.values().forEach(value => {
if (!otherSet.has(value)) {
differenceSet.add(value);
}
});
return differenceSet;
}
// 子集
isSubsetOf(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;
}
}

这里就不再演示Set类中方法的使用了,有兴趣的可以自己做个demo测试一下,如果有任何的问题,欢迎评论区留言。

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信