JavaScript——哈希表(链地址法)
function HashTable(){
this.storage = []
this.count = 0
this.limit = 7
HashTable.prototype.hashFunc = function(key, size){
let hashCode = 0
key = String(key)
for (let i =0; i < key.length; i++){
hashCode = 37 * hashCode + key.charCodeAt(i)
}
let index = hashCode % size
return index
}
HashTable.prototype.put = function(key, value){
let index = this.hashFunc(key, this.limit)
let bucket = this.storage[index]
if (bucket){
for (let i = 0; i < bucket.length; i++){
let tuple = bucket[i]
if (tuple[0] == key){
tuple[1] = value
return
}
}
bucket.push([key, value])
}
else{
bucket = []
this.storage[index] = bucket
bucket.push([key, value])
}
this.count += 1
if (this.count > this.limit * 0.75){
let newLimit = this.getPrime(this.limit * 2)
this.resize(newLimit)
}
}
HashTable.prototype.get = function(key){
let index = this.hashFunc(key, this.limit)
let bucket = this.storage[index]
if (bucket){
for (let i =0; i < bucket.length; i++){
let tuple = bucket[i]
if (tuple[0] == key){
return tuple[1]
}
}
}
return null
}
HashTable.prototype.remove = function(key){
let index = this.hashFunc(key, this.limit)
let bucket = this.storage[index]
if (bucket){
for (let i = 0; i < bucket.length; i++){
let tuple = bucket[i]
if (tuple[0] == key){
bucket.splice(i, 1)
this.count -= 1
if (this.limit > 7 && (this.count < this.limit * 0.25)){
let newLimit = this.getPrime(parseInt(this.limit / 2))
this.resize(newLimit)
}
return tuple[1]
}
}
}
return null
}
HashTable.prototype.isPrime = function(num){
let sqrtNum = parseInt(Math.sqrt(num))
for (let i = 2; i <= sqrtNum; i++){
if (num % i == 0){
return false
}
}
return true
}
HashTable.prototype.getPrime = function(num){
while (this.isPrime(num) == false){
num += 1
}
return num
}
HashTable.prototype.resize = function(newLimit){
let oldStorage = this.storage
this.storage = []
this.count = 0
this.limit = newLimit
for (let i =0; i < oldStorage.length; i++){
let bucket = oldStorage[i]
if (bucket){
for (let y = 0; y < bucket.length; y++){
let tuple = bucket[y]
this.put(tuple[0], tuple[1])
}
}
}
}
}