function HashTable() {
this.storage = []
this.count = 0
this.limit = 7
HashTable.prototype.hashFunc = function(str, size) {
var hashCode = 0
for(var i = 0; i < str.length; i++){
hashCode = 37 * hashCode + str.charCodeAt(i)
}
var index = hashCode % size
return index
}
HashTable.prototype.put = function(key, value) {
var index = this.hashFunc(key, this.limit)
var bucket = this.storage[index]
if (bucket == null) {
bucket = []
this.storage[index] = bucket
}
for (var i=0; i<bucket.length;i++) {
var tuple = bucket[i]
if (tuple[0] == key) {
tuple[1] = value
return
}
}
bucket.push([key, value])
this.count++
if (this.count > this.limit * 0.7
JavaScript数据结构之哈希表的封装
最新推荐文章于 2024-09-10 09:55:59 发布
本文详细介绍了如何使用JavaScript封装哈希表数据结构,包括添加、修改和删除操作,并确保容量始终保持为质数。
摘要由CSDN通过智能技术生成