logo头像

孙宇

JavaScript集合(Set)

一、概念

  • 集合:集合是由一组无序且唯一的项组成的。

二、知识碎点

  • in运算符 验证给定的元素是否在对象上的属性。(原型链上有都会返回true)
  • Object.prototype.hasOwnProperty.call(Obj,element)。 (只是当前对象,不含原型链上的属性和方法)

三、具体实现

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
104
class Set {
constructor() {
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;
}

has(element) {
return Object.prototype.hasOwnProperty.call(this.items, element);
}

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();
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;
}

isEmpty() {
return this.size() === 0;
}

size() {
return Object.keys(this.items).length;
}

clear() {
this.items = {};
}

toString() {
if (this.isEmpty()) {
return '';
}
const values = this.values();
let objString = `${values[0]}`;
for (let i = 1; i < values.length; i++) {
objString = `${objString},${values[i].toString()}`;
}
return objString;
}
}