集合是由一组无序且唯一(即不能重复)的项组成的。
-
add(value):向集合添加一个新的项。
-
delete(value):从集合移除一个值。
-
has(value):如果值在集合中,返回true,否则返回false。
-
clear():移除集合中的所有项。
-
size():返回集合所包含元素的数量。与数组的length属性类似。
-
values():返回一个包含集合中所有值的数组。
并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合。
交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合。
差集:对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集合的元素的新集合。
子集:验证一个给定集合是否是另一集合的子集。
class Set {
constructor() {
this.items = {};
}
has(value) {
return this.items.hasOwnProperty(value);
}
add(value) {
if (!this.has(value)) {
this.items[value] = value;
return true;
} else {
return false;
}
}
remove(value) {
if (this.has(value)) {
delete this.items[value];
return true;
} else {
return false;
}
}
clear() {
this.items = {};
}
size() {
let count = 0;
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
++count;
}
}
return count;
}
keys() {
let keys = [];
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
values() {
let values = [];
for (let value in this.items) {
if (this.items.hasOwnProperty(value)) {
values.push(this.items[value]);
}
}
return values;
}
}
// 并集 A U B
Set.prototype.union = function (otherSet) {
let unionSet = new Set();
let values = this.values();
for (let i = 0; i < values.length; i++) {
unionSet.add(values[i]);
}
values = otherSet.values();
for (let i = 0; i < values.length; i++) {
unionSet.add(values[i]);
}
return unionSet;
}
// 交集 A ∩ B
Set.prototype.intersection = function (otherSet) {
let intersectionSet = new Set();
let values = this.values();
for (let i = 0; i < values.length; i++) {
if (otherSet.has(values[i])) {
intersectionSet.add(values[i]);
}
}
return intersectionSet;
}
// 差集 A-B
Set.prototype.difference = function (otherSet) {
let differenceSet = new Set();
let values = this.values();
for (let i = 0; i < values.length; i++) {
if (!otherSet.has(values[i])) {
differenceSet.add(values[i]);
}
}
return differenceSet;
}
// 子集 A⊆B
Set.prototype.subset = function (otherSet) {
if (this.size() > otherSet.size()) {
return false;
} else {
let values = this.values();
for (let i = 0; i < values.length; i++) {
if (!otherSet.has(values[i])) {
return false;
}
}
return true;
}
}
let set = new Set();
set.add(1);
set.add(2);
// set.add(5);
// set.add(9);
console.log(set); // Set { items: { '1': 1, '2': 2 } }
console.log(set.keys()); // [ '1', '2' ]
console.log(set.values()); // [ 1, 2 ]
console.log(set.size()); // 2
set.remove(1);
console.log(set); // Set { items: { '2': 2 } }
let otherset = new Set();
otherset.add(1);
otherset.add(2);
otherset.add(3);
otherset.add(4);
console.log(set.union(otherset)); // Set { items: { '1': 1, '2': 2, '3': 3, '4': 4 } }
console.log(set.intersection(otherset)); //Set { items: { '2': 2 } }
console.log(set.difference(otherset)); // Set { items: {} }
console.log(set.subset(otherset)); // true