字典

173 阅读1分钟
  • 集合表示一组互不相同的元素(不重复的元素)。在字典中,存储的是[键,值]对,其中键名是用来查询特定元素的。字典和集合很相似,集合以[值,值的形式存储元素,字典则是以[键,值]的形式来存储元素。字典也称作映射、符号表或关联数组。
  • 在计算机科学中,字典常常用来保存对象的引用地址。

function defaultToString(item) {
  if (item === null) {
    return 'NULL'
  } else if (item === undefined) {
    return 'UNDEFINED'
  } else if (typeof item === 'string' || item instanceof String) {
    return `${item}`
  }
  return item.toString()
}

class ValuePair{
  constructor(key, value) {
    this.key = key
    this.value = value
  }
  toString() {
    return `[#{this.key}: ${this.value}]`
  }
}

class Dictionary{
  constructor(toStrFn = defaultToString) {
    this.toStrFn = toStrFn
    this.table = {}
  }
  hasKey(key) {
    return this.table[this.toStrFn(key)] != null
  }
  set(key, value) {
    if (key !== null && key != null) {
      const tableKey = this.toStrFn(key)
      this.table[tableKey] = new ValuePair(key,value)
      return true
    }
    return false
  }
  remove(key) {
    if (this.hasKey(key)) {
      delete this.table[this.toStrFn(key)]
      return true
    }
    return false
  }
  get(key) {
    if (this.hasKey(key)) {
      return this.table[this.toStrFn(key)]
    }
    return undefined
  }
  keyValues() {
    const valuePairs = []
    for (const k in this.table) {
      if (this.hasKey(k)) {
        valuePairs.push(this.table[k])
      }
    }
    return valuePairs
  }
  keys() {
    return this.keyValues().map(ValuePair => valuePair.key)
  }
  values() {
    return this.keyValues().map(valuePair => valuePair.value)
  }
  forEack(callbackFn) {
    const valuePairs = this.keyValues()
    for (let i = 0; i < valuePairs.length; i++){
      const result = callbackFn(valuePairs[i].key,valuePairs[i].value)
      if (result === false) {
        break
      }
    }
  }
  clear() {
    this.table = {}
  }
  size() {
    return Object.keys(this.table).length
  }
  isEmpty() {
    return this.size() === 0
  }
  toString() {
    if (this.isEmpty()) {
      return ''
    }
    const valuePairs = this.keyValues()
    let objString = `{valuePairs[0].toString()}`
    for (let i = 0; i < valuePairs.length; i++){
      objString = `${objString},${valuePairs[i].toString()}`
    }
    return objString
  }
}