集合是由一组无序且唯一(即不能重复)的项组成的
集合运算:
-
并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合
-
交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合
-
差集:对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集合的元素的新集合(意思就是存在于A中,但不存在于B中)
-
子集:验证一个给定集合是否是另一个集合的子集(意思就是集合A中的每一个元素,也需要存在于集合B)
class Set {
constructor() {
this.items = {}
}
// 判断元素是否存在集合中,存在返回 true,否则返回 false
has(element) {
// Object 的原型有 hasOwnProperty 方法,该方法返回一个表明对象是否具有特定属性的布尔值。
return Object.prototype.hasOwnProperty.call(this.items, element)
// in 运算符则返回表示对象在原型链上是否有特定属性的布尔值
// return element in this.items
// 我们在代码中也可以使用如下的方法,但是,如果这样的话,ESLint 会抛出一个错误:
// 错误的原因为:不是所有的对象都继承了Object.property,甚至继承了Object.property的对象上的hasOwnProperty 方法也有可能被覆盖,导致代码不能正常工作。
// return this.items.hasOwnProperty(element)
}
// 向集合中新增加一个元素
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 = {}
}
// 返回集合中元素的个数
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()
const otherValues = otherSet.values()
let biggerSet = values
let smallerSet = otherValues
if (values.length < otherValues.length) {
biggerSet = otherValues
smallerSet = values
}
smallerSet.forEach((value) => {
if (biggerSet.includes(value)) {
intersectionSet.add(value)
}
})
return intersectionSet
}
// 交集
// intersection(otherSet) {
// const intersectionSet = new Set()
// this.values().forEach(values => {
// if (otherSet.has(values)) {
// intersectionSet.add(values)
// }
// })
// 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
}
}
const set = new Set()
set.add(1)
set.add(3)
set.add(5)
console.log(set.size());
set.delete(3)
console.log(set.has(5));
console.log(set.values());
const setA = new Set()
setA.add(1)
setA.add(2)
setA.add(3)
setA.add(4)
const setB = new Set()
setB.add(2)
setB.add(3)
setB.add(4)
setB.add(5)
const setC = new Set()
setC.add(3)
setC.add(4)
setC.add(5)
console.log(setA.union(setB).values());
console.log(setA.intersection(setB).values());
console.log(setA.difference(setB).values());
console.log(setC.isSubsetOf(setB));
console.log(setC.isSubsetOf(setA));