一、定义
集合是由一组无序且唯一(即不能重复)的项组成的。这个数据结构使用了与有限集合相同 的数学概念,但应用在计算机科学的数据结构中。我们使用对象而不是数组来表示集合。
二、实现
function Set() {
const items = {};
this.add = function(value) {
if (this.has(value)) {
return false;
}
const key = this.setKey(value);
items[key] = value;
return true;
};
this.remove = function(value) {
if (!this.has(value)) {
return false;
}
const key = this.setKey(value);
delete(key);
};
this.clear = () => {
items = {};
return true;
};
this.size = () => Object.keys(items);
this.values = () => Object.values(items);
this.has = (value) => items.hasOwnProperty(value);
this.setKey = (value) => `${typeof(value)}_${value}`;
// 交集
this.intersection = function(otherSet) {
const intersectionSet = new Set();
this.values().forEach((item) => {
if (otherSet.has(item)) {
intersectionSet.add(item);
}
});
return intersectionSet;
}
// 差集
this.difference = function(otherSet) {
const differenceSet = new Set();
this.values().forEach((item) => {
if (!otherSet.has(item)) {
differenceSet.add(item);
}
})
}
// 并集
this.union = (otherSet) => ({ ...items, ...otherSet });
// 子集 A是B的子集
this.subset = function(otherSet) {
if (this.size() > otherSet.size()) {
return false;
}
const temp = this.values().find((item) => !otherSet.has(item));
return !!temp;
}
}