JavaScript - 集合
小于 1 分钟
JavaScript - 集合
基于 ES2015 创建集合类
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 element in this.items;
return Object.prototype.hasOwnProperty.call(this.items, element);
}
clear() {}
size() {
let count = 0;
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
count += 1;
}
}
return count;
}
values() {
let values = [];
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
values.push(key);
}
}
return values;
}
// 并集
union(otherSet) {
const unionSet = new Set();
let values = this.values();
for (let i = 0; i < values.length; i += 1) {
unionSet.add(values[i]);
}
values = otherSet.values;
for (let i = 0; i < values.length; i += 1) {
unionSet.add(values[i]);
}
return unionSet;
}
// 交集
intersection(otherSet) {
const intersectionSet = new Set();
const values = this.values();
for (let i = 0; i < values.length; i += 1) {
if (otherSet.has(values[i])) {
intersectionSet.add(values[i]);
}
}
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;
}
}