<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>哈希表</title>
</head>
<body>
<script>
function hashTable(){
//属性
this.storage = [];
this.count = 0;//用于计算loadFactor>0.75 扩容 <0.25减小容量
this.limit = 7;//长度尽量设置为质数
//方法
//hash函数
hashTable.prototype.hashFunc = function(str,size){
//1定义hashCode
var hashCode = 0;
//2,霍纳算法,计算hashCode
for(var i = 0;i < str.length;i++){
hashCode = 37*hashCode+ str.charCodeAt(i); //获取Unicode编码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 = new Array();
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 +=1;
if(this.count > this.limit *0.75){
var newSize = Math.floor(this.limit *2);
var newprime = this.getPrimeNumber(newSize);
this.resize(newprime);
}
}
//获取值
hashTable.prototype.get = function (key) {
var index = this.hashFunc(key,this.limit);
var bucket = this.storage[index];
if (bucket ==null) return null;
for(var i = 0; i < bucket.length;i++){
var tuple = bucket[i];
if(tuple[0]== key){
return tuple[1];
}
}
return null;
}
//删除元素
hashTable.prototype.remove = function(key){
var index = this.hashFunc(key,this.limit);
var bucket = this.storage[index];
if (bucket == null) return null;
for(var i = 0; i < bucket.length;i ++){
var tuple = bucket[i];
if(tuple[0] == key){
bucket.splice(i,1);
this.count--;
if (this.limit >7 && this.count < this.limit *0.25){
var newSize = Math.floor(this.limit /2);
var newprime = this.getPrimeNumber(newSize);
this.resize(newprime);
}
return tuple[1];
}
}
return null;
}
hashTable.prototype.isEmpty = function () {
return this.count == 0;
}
//获取元素个数
hashTable.prototype.size = function () {
return this.count;
}
hashTable.prototype.resize = function (newlimit) {
var oldStorage = this.storage;
this.storage = [];
this.count = 0;
this.limit = newlimit;
for(var i = 0; i < oldStorage.length; i++){
var bucket = oldStorage[i];
if(bucket == null) continue;
for(var j = 0;j < bucket.length;j++){
var tupple = bucket[j];
this.put(tupple[0],tupple[1]);
}
}
}
hashTable.prototype.getPrimeNumber = function(num){
while (!this.isPrimeNumber(num)){
num ++;
}
return num;
}
//判断质数
hashTable.prototype.isPrimeNumber = function(num){
var sqrt = parseInt(Math.sqrt(num))/**开平方根*/
for(var i = 2; i<= sqrt;i++){
if (num %i == 0)return false;
}
return true;
}
}
var hashTable = new hashTable();
hashTable.put('1','a');
hashTable.put('2','b');
hashTable.put('3','c');
hashTable.put('4','d');
hashTable.put('6','f');
hashTable.put('7','f');
hashTable.put('8','G');
hashTable.put('9','h');
hashTable.put('10','i');
alert(hashTable.get('1'));
alert(hashTable.remove('1'));
// hashTable.resize(2*hashTable.limit);
console.log(hashTable);
</script>
</body>
</html>