/*
概念:
集合是由一组无序且唯一(即不能重复)的项组成的;
方法:
add(element):向集合添加一个新元素。
delete(element):从集合移除一个元素。
has(element):如果元素在集合中,返回 true,否则返回 false。
clear():移除集合中的所有元素。
size():返回集合所包含元素的数量。它与数组的 length 属性类似。
values():返回一个包含集合中所有值(元素)的数组。
*/
class Set {
constructor() {
this.items = {};
}
has(element) {
/*
Object 原型有 hasOwnProperty 方法。该方法返回一个表明对象是否具有特定属性的布尔
值。in 运算符则返回表示对象在原型链上是否有特定属性的布尔值。
*/
// return element in items;
return Object.prototype.hasOwnProperty.call(this.items, 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;
}
sizeLegacy() {
let count = 0;
for (let key in this.items) {
/*
还需要使用 has 方法(以验证 items 对象具有该属性),因为对象的原
型包含了额外的属性(属性既有继承自 JavaScript 的 Object 类的,也有属于对
象自身、未用于数据结构的)
*/
if (this.items.hasOwnProperty(key)) {
count++;
}
}
return count;
}
values() {
/*
Object.values()方法返回了一个包含给定对象所有属性值的数组。它是在
ECMAScript 2017 中被添加进来的,目前只在现代浏览器中可用
*/
return Object.values(this.items);
}
valuesLegacy() {
let values = [];
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
values.push(key);
}
}
return values;
}
// 并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合。
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(valuesp[i])) {
intersectionSet.add(values[i])
}
}
return intersectionSet;
}
// 优化代码--迭代元素的次数更少--意味着更少的过程消耗
intersectionTwo(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;
}
// 差集:包含所有存在于第一个集合且不存在于第二个集合的元素的新集合(所有存在于集合 A 但不存在于集合 B 的元素)
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;
}
/*
只要回调函数返回 true,every 方法就会被调用。如果
回调函数返回 false,循环会停止
*/
let isSubset = true;
this.values().every(value => {
if (!otherSet.has(value)) {
isSubset = false;
return false;
}
return true;
});
return isSubset;
}
}