|
| 1 | +// XSet because ES6 already has a Set class |
| 2 | +class XSet { |
| 3 | + constructor() { |
| 4 | + this.data = {}; |
| 5 | + } |
| 6 | + |
| 7 | + add(element) { |
| 8 | + if (!this.data[element]) { |
| 9 | + this.data[element] = true; |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + remove(element) { |
| 14 | + if (this.data[element]) { |
| 15 | + delete this.data[element]; |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + has(element) { |
| 20 | + return !!this.data[element]; |
| 21 | + } |
| 22 | + |
| 23 | + values() { |
| 24 | + return Object.keys(this.data); |
| 25 | + } |
| 26 | + |
| 27 | + union(givenSet) { |
| 28 | + const result = new Set(); |
| 29 | + const firstSetValues = this.values(); |
| 30 | + const givenSetValues = givenSet.values(); |
| 31 | + |
| 32 | + // eslint-disable-next-line no-restricted-syntax |
| 33 | + for (const e of firstSetValues) result.add(e); |
| 34 | + |
| 35 | + // eslint-disable-next-line no-restricted-syntax |
| 36 | + for (const e of givenSetValues) result.add(e); |
| 37 | + |
| 38 | + return result; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// const s = new XSet(); |
| 43 | + |
| 44 | +// s.add(10); |
| 45 | +// s.add(20); |
| 46 | +// s.add(90); |
| 47 | + |
| 48 | +// console.log(s.has(1)); |
| 49 | +// console.log(s.has(10)); |
| 50 | +// console.log(s.has(90)); |
| 51 | + |
| 52 | +// console.log(s.values()); |
| 53 | +// s.remove(90); |
| 54 | +// console.log(s.has(90)); |
| 55 | +// console.log(s.data); |
| 56 | + |
| 57 | +module.exports = XSet; |
0 commit comments