运用Ts实现Set的几个作用处理和子集
原创直接转到代码, 这个地方不难 如果你感兴趣,你可以自己动手。
class MySet {
items: any;
constructor() {
this.items = {};
}
has(element: any) {
return Object.prototype.hasOwnProperty.call(this.items, element);
}
union(otherSet: MySet) {
const unionSet = new MySet();
this.values().forEach((value) => unionSet.add(value));
otherSet.values().forEach((value) => unionSet.add(value));
return unionSet;
}
values() {
return Object.values(this.items);
}
size() {
return Object.keys(this.items).length;
}
add(element: any) {
if (!this.has(element)) {
this.items[element] = element;
return true;
}
return false;
}
}
const setA = new MySet();
setA.add(1);
setA.add(2);
setA.add(3);
setA.add(3);
console.log(setA);
const setB = new MySet();
setB.add(3);
setB.add(4);
setB.add(5);
console.log(setB);
const unionAB = setA.union(setB);
console.log(unionAB.values());
结果截图:
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除