Skip to content

Latest commit

 

History

History
113 lines (98 loc) · 2.35 KB

File metadata and controls

113 lines (98 loc) · 2.35 KB

第7章 集合

概念

集合是由一组无序且唯一的项组成。

不是所有的对象都继承了 Object.prototype,甚至继承了 Object.prototype 的对象上的 hasOwnProperty 方法也有可能被覆盖,导致代码不能正常工作。要避免出现问题,使用 Object.prototype.hasOwnProperty.call 是更安全的做法。

集合实现

class Set {
  constructor() {
    this.items = {}
  }

  add(element) {
    if (!this.has(element)) {
      this.items[element] = element
      return true
    }
    return false
  }

  delete(element) {
    if (this.has(element)) {
      delete this.items[element]
      return true
    }
    return false
  }

  has(element) {
    return Object.prototype.hasOwnProperty.call(this.items, element)
  }

  values() {
    return Object.values(this.items)
  }

  union(otherSet) {
    const unionSet = new Set()
    this.values().forEach(value => unionSet.add(value))
    otherSet.values().forEach(value => unionSet.add(value))
    return unionSet
  }

  intersection(otherSet) {
    const intersectionSet = new Set()
    const values = this.values()
    const otherValues = otherSet.values()
    let biggerSet = values
    let smallerSet = otherValues
    if (otherValues.length - values.length > 0) {
      biggerSet = otherValues
      smallerSet = values
    }
    smallerSet.forEach(value => {
      if (biggerSet.includes(value)) {
        intersectionSet.add(value)
      }
    })
    return intersectionSet
  }

  difference(otherSet) {
    const differenceSet = new Set()
    this.values().forEach(value => {
      if (!otherSet.has(value)) {
        differenceSet.add(value)
      }
    })
    return differenceSet
  }

  isSubsetOf(otherSet) {
    if (this.size() > otherSet.size()) {
      return false
    }
    let isSubset = true
    this.values().every(value => {
      if (!otherSet.has(value)) {
        isSubset = false
        return false
      }
      return true
    })
    return isSubset
  }

  isEmpty() {
    return this.size() === 0
  }

  size() {
    return Object.keys(this.items).length
  }

  clear() {
    this.items = {}
  }

  toString() {
    if (this.isEmpty()) {
      return ""
    }
    const values = this.values()
    let objString = `${values[0]}`
    for (let i = 1; i < values.length; i++) {
      objString = `${objString},${values[i].toString()}`
    }
    return objString
  }
}