skip to content

The Algorithms
实现一个集合

class CustomSet {
  constructor() {
    this.items = {}
  }
  getKeyForValue(value) {
    return Symbol.for(value)
  }
  add(value) {
    if (!this.has(value)) this.items[this.getKeyForValue(value)] = value
    return this
  }
  clear() {
    this.items = {}
  }
  delete(value) {
    if (this.has(value)) delete this.items[this.getKeyForValue(value)]
  }
  has(value) {
    const key = this.getKeyForValue(value)
    const keyList = Object.getOwnPropertySymbols(this.items)
    return keyList.some(item => item === key)
  }
  size() {
    return Object.getOwnPropertySymbols(this.items).length
  }
  values() {
    return Object.getOwnPropertySymbols(this.items).map(key => this.items[key])
  }
  // 并集
  union(otherSet) {
    const unionSet = new CustomSet()
    this.values().forEach(values => unionSet.add(values))
    otherSet.values().forEach(values => unionSet.add(values))
    return unionSet
  }
  // 交集
  intersection(otherSet) {
    const intersectionSet = new CustomSet()
    this.values().forEach(value => {
      if (otherSet.has(value)) {
        intersectionSet.add(value)
      }
    })
    return intersectionSet
  }
  // 差集
  difference(otherSet) {
    const differenceSet = new CustomSet()
    this.values().forEach(value => {
      if (!otherSet.has(value)) {
        differenceSet.add(value)
      }
    })
    return differenceSet
  }
  // 子集
  isSubsetOf(otherSet) {
    if (this.size() > otherSet.size()) return false
    return this.values().every(value => {
      return otherSet.has(value)
    })
  }
}

const s1 = new CustomSet()
s1.add(1).add(2).add(3).add(4)
const s2 = new CustomSet()
s2.add('Jack').add('Tim').add('David')
const s3 = s1.union(s2)
console.log('======================================')
console.log(s3.values())
const s4 = new CustomSet()
s4.add(3).add(4).add(5).add(6)
const s5 = s1.intersection(s4)
console.log('======================================')
console.log(s5.values())
console.log('======================================')
const s6 = s1.difference(s4)
console.log(s6.values())
console.log('======================================')
const s7 = new CustomSet()
s7.add(1).add(2).add(3).add(4).add(5).add(6)
console.log(s1.isSubsetOf(s7))