实现一个快速查找功能的集合(容器)

180 阅读1分钟
class Container {
  static items = []
  has(val) {
    return this.values().includes(val)
  }
  add(val) {
    if (!this.has(val)) {
      Container.items.push(val)
      return true
    }
    return false
  }
  remove(val) {
    const index = this.values().findIndex(v => v === val)
    if (index > -1) {
      Container.items.splice(index, 1)
      return true
    }
    return false
  }
  values() {
    return Container.items
  }
  size() {
    return this.values().length
  }
  clear() {
    Container.items = []
  }
  quickFind(val) {
    const find = (val, values) => {
      const [first] = values
      const left = []
      const right = []
      for (let i = 0; i < values.length; i++) {
        if (values[i] < first) {
          left.push(values[i])
        }
        if (values[i] > first) {
          right.push(values[i])
        }
      }
      if (val === first) {
        return val
      } else if (val < first) {
        if (left.length) {
          return find(val, left)
        }
      } else {
        if (right.length) {
          return find(val, right)
        }
      }
    }
    return find(val, this.values())
  }
}

c = new Container()
c.add(1)
c.add(8)
c.values()
c.quickFind(8)