关于javascript:数据结构JavaScript-HashTable-实现

35次阅读

共计 913 个字符,预计需要花费 3 分钟才能阅读完成。

实现思路

残缺可运行代码

class HashTable {constructor() {
    this.tableSize  = 10000007
    this.table = new Array(this.tableSize).fill(0)
  }
  _hash(s) {
    let n = 1
    let f = 1
    let arr = s.split('')
    for(let i in arr) {n += arr[i].charCodeAt() * f
      f *= 10
    }
    return n
  }
  _index(k) {return this._hash(k)
  }
  _insert_at_index(index, k, v) {// console.log(index)
    // console.log(this.table[index])
    let tmp = this.table[index]
    let data = [k, v]
    // console.log('tmp', tmp)
    // console.log(data)
    if(tmp === 0) {this.table[index] = [data]
    } else {this.table[index].push([data])
    }
  }
  set(k, v) {let index = this._index(k)
    this._insert_at_index(index, k, v)
  }
  // 
  get(k) {let index = this._index(k)
    // console.log('index', index)
    let tmp = this.table[index]
    // console.log('tmp', tmp)
    if(tmp instanceof Array) {for(let kv in tmp) {if(tmp[kv][0] === k) {return tmp[kv][1]
        }
      }
    }
    return null
  }
}
// 
let ht = new HashTable()
let names = ['tao', 'gua', 'wu']

for(let i in names) {
  let v = i
  ht.set(names[i], v)
  console.log('set', names[i], v)
}
for(let j in names) {let v = ht.get(names[j])
  console.log('get', names[j], v) 
}

正文完
 0