'use strict'
const md5 = require('blueimp-md5');
class Set {
constructor() {
this.items = {}
}
has(value) {
return this.items.hasOwnProperty(md5(JSON.stringify(value)));
}
add(value) {
const key = md5(JSON.stringify(value));
if (!this.has(key)) {
this.items[key] = value;
return true;
}
return false;
}
remove(value) {
const key = md5(JSON.stringify(value));
if (this.has(key)) {
delete this.items[key];
return true;
}
return false;
}
clear() {
this.items = {};
}
size() {
return Object.keys(this.items).length;
}
values() {
let values = [];
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
values.push(this.items[key]);
}
}
return values;
}
union(otherSet) {
let unionSet = new Set();
let values = this.values();
for (let value of values) {
unionSet.add(value);
}
values = otherSet.values();
for (let value of values) {
unionSet.add(value);
}
return unionSet;
}
intersertion(otherSet) {
let intersertionSet = new Set();
for (let key in this.items) {
if (otherSet.has(this.items[key])) {
intersertionSet.add(this.items[key]);
};
}
return intersertionSet;
}
difference(otherSet) {
let differenceSet = new Set();
for (let key in this.items) {
if (!otherSet.has(this.items[key])) {
differenceSet.add(this.items[key]);
}
}
return differenceSet;
}
isSubset(otherSet) {
if (this.size() > otherSet.size()) {
return false;
} else {
for (let key in this.items) {
if (!otherSet.has(this.items[key])) {
return false;
}
}
return true;
}
}
}
const s = new Set();
const se = new Set();
s.add('2121');
s.add({ 'dede': 'dede' });
s.add({ 'dede': 'dede' });
se.add({ 'fee': 'fee' });
se.add('2121');
s.isSubset(se);
console.log(s.isSubset(se));
console.log(s.intersertion(se));
console.log(s.union(se).values());
console.log(s.difference(se).values());
集合
最新推荐文章于 2022-09-04 11:18:52 发布