Js实现哈希表
前言
哈希表的原理:https://zhuanlan.zhihu.com/p/95156642
这非常重要
一、hashTable?
“散列表(Hash table,也叫哈希表),是根据键(Key)而直接访问在内存存储位置的数据结构。也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。这个映射函数称做散列函数,存放记录的数组称做散列表。
二、Js代码实现hashTable
1.核心代码
class hashTable {
//数组 + 数组(链表)
constructor() {
this.limit = 7
this.store = []
this.count = 0
}
//哈希函数:传入数据的key,得数据存放的下标
//里面的算法可以自己定义
hashFunc(key, size) {
let hashCode = 0
//计算hashCode的值 -- 霍纳算法
for (let i = 0; i < key.length; i++) {
hashCode = 37 * hashCode + key.charCodeAt(i)
}
//取余,找到存放数组的下标
const index = hashCode % size
return index
}
//往hashTable里面添加元素
put(key, value) {
//1.根据key获取对应的index
const index = this.hashFunc(key, this.limit)
//根据index取出对应的数据(bucket)
let bucket = this.store[index] ?? null
//判断对应位置有无数据
if (bucket === null) {
bucket = []
this.store[index] = bucket
}
//添加数据,也可能需要修改
for (let i = 0; i < bucket.length; i++) {
let tuple = bucket[i]
if (tuple?.key === key) {
tuple.value = value
return
}
}
//进行添加操作 --这里使用数组(经常插入修改使用链表效率更高)
bucket.push({ key, value })
this.count++
}
//查询
get(key) {
//1.根据key获取对应的index
const index = this.hashFunc(key, this.limit)
//根据index取出对应的数据(bucket)
let bucket = this.store[index] ?? null
//判断对应位置有无数据
if (bucket === null) {
return null
}
for (let i = 0; i < bucket.length; i++) {
let tuple = bucket[i]
if (tuple?.key === key) {
return tuple.value
}
}
return null
}
//删除
delete(key) {
//1.根据key获取对应的index
const index = this.hashFunc(key, this.limit)
//根据index取出对应的数据(bucket)
let bucket = this.store[index] ?? null
//判断对应位置有无数据
if (bucket === null) {
return false
}
for (let i = 0; i < bucket.length; i++) {
let tuple = bucket[i]
if (tuple?.key === key) {
bucket.splice(i, 1)
this.count--
return true
}
}
return false
}
//元素个数
size() {
return this.count;
}
//打印看结果
toValue() {
console.log(this.store)
}
}
2.测试代码
代码如下(示例):
const list = [
{ key: 'adc', value: 123 },
{ key: 'acb', value: 234 },
{ key: 'bac', value: 42 },
{ key: 'aaa', value: 23 },
{ key: 'ccc', value: 6 },
{ key: 'ddd', value: 9 },
{ key: 'ddrd', value: 9 },
]
const ht = new hashTable()
list.map(item => (ht.put(item.key, item.value)))
ht.toValue()
console.log("get", ht.get('adc'))
console.log("get", ht.get('lll'))
ht.delete('aaa')
ht.toValue()
console.log("get", ht.get('aaa'))
该处使用的url网络请求的数据。
总结
这里我用Js实现了hashTable,其实实现起来很简单,主要是相关的原理会花很多时间去理解,关于数组扩容和减容的内容我后续会出