参考学习link
function HashTable() {
this.storage = []
this.count = 0
this.limit = 7
// 哈希函数
HashTable.prototype.hashFunc = function(str, size) {
// 定义hashCode变量
let hashCode = 0
//2.根据霍纳算法,计算hashCode的值
//借助Unicode编码计算
for (let i = 0; i < str.length; i++) {
hashCode = 37 * hashCode + str.charCodeAt(i)
}
var index = hashCode % size
return index
}
// 添加元素
hashCode.prototype.put = function(key, value) {
//1.根据key获取对应的index
var index = this.hashFunc(key, this.limit)
//2.根据index取得对应的bucket(bucket是key的hashCode对应下表位置)
let bucket = this.storage[index]
//3.判断当前bucket是否为空
if (bucket === null) {
bucket = []
this.storage[index] = bucket
}
//4.判断是否修改数据
for (let i = 0; i < bucket.length; i++) {
let tuple = bucket[i]
if (tuple[0] === key) {
tuple [1] = value
return
}
}
//5.当前bucket(链表)中没有该数据,就直接添加该数据
bucket.push([key, value])
this.count += 1
}
// 获取元素
HashTable.prototype.get = function(key) {
// 1.根据key,获得index;
let index = this.hashFunc(key, this.limit)
// 2.根据index,获得bucket;
let bucket = this.storage[index]
// 3.判断bucket是否为null,为null就直接返回null
if (bucket === null) {
return null
}
// 4.bucket不为null,则遍历找到对应的key
for (let i = 0; i < bucket.length; i++) {
let tuple = bucket[i]
if (tuple[0] === key) {
return tuple[1]
}
}
// 5.遍历完后,没有找到对应的key,就返回null
return null
}
// 删除元素
HashTable.prototype.remove = function(key) {
// 根据key值,获取index
let index = this.hashFunc(key, this.limit)
// 根据index获取bucket
this.bucket = this.storage[index]
// 判断bucket是否为null,是则返回null
if (bucket === null) {
return null
}
// 4.bucket不为null,则遍历找到对应的值,删除
for (let i = 0; i < bucket.length; i++) {
let tuple = bucket[i]
if (tuple[0] === key) {
// 删除元素
bucket.splice(i, 1)
// count减一
this.count--
return tuple[1]
}
}
return null
}
// 判断hashTable是否为空
HashTable.prototype.isEmpty = function() {
return this.count === 0
}
// 当前hashTable的长度
HashTable.prototype.size = function() {
return this.count
}
}