class FakeSet {
constructor(arr=[]) {
this.items = {};
this.size = 0;
arr.forEach((item) => {
this.add(item);
})
}
has(val) {
return this.items.hasOwnProperty(val);
}
add(val) {
if (!this.has(val)) {
this.items[val] = val;
this.size++ ;
return true;
} else {
return false;
}
}
delete(val) {
if (this.has(val)) {
Reflect.deleteProperty(this.items, val);
this.size--;
return true;
} else {
return false;
}
}
clear() {
this.items = {};
this.size = 0;
}
keys() {
return Object.keys(this.items);
}
values() {
return Object.values(this.items);
}
forEach(fn, context) {
for (let i = 0; i<this.size; i++) {
let key = Object.keys(this.items)[i];
Reflect.apply(fn, context, [key, this.items[key]])
}
}
union(other) {
let union = new FakeSet();
let values = this.values();
values.forEach(item => {
union.add(item);
});
let otherValues = other.values();
otherValues.forEach(item => {
union.add(item);
});
return union;
}
intersect(other) {
let intersect = new FakeSet();
let values = this.values();
values.forEach(item => {
if (other.has(item)) {
intersect.add(item);
}
});
return intersect;
}
difference(other) {
let difference = new FakeSet();
let values = this.values();
values.forEach(item => {
if (!other.has(item)) {
difference.add(item);
}
});
return difference;
}
subset(other) {
if (this.size > other.size) {
return false;
} else {
let values = this.values;
values.forEach(item => {
if (!other.has(item)) {
return false;
}
})
return true;
}
}
}
let set = new FakeSet([5, 6, 7, 1]);
set.add(1);
set.add(4);
set.add('3')
set.forEach((key, value) => {
console.log(key + ':' + value);
});
console.log(set.values());
console.log(set.union(new FakeSet([1, 2, 3, 4])))
ES6 Set集合实现
最新推荐文章于 2022-07-12 16:33:02 发布