封装哈希表
哈希表的常见操作为:
put(key,value):插入或修改操作;
get(key):获取哈希表中特定位置的元素;
remove(key):删除哈希表中特定位置的元素;
isEmpty():如果哈希表中不包含任何元素,返回trun,如果哈希表长度大于0则返回false;
size():返回哈希表包含的元素个数;
resize(value):对哈希表进行扩容操作;
/**
*
* 实现哈希表 CRUD
*
* */
function HashTable(){
this.table = [];
//元素数量
this.count = 0;
//哈希表大小
this.size = 7;
//哈希函数
function HashFunc(str, size) {
let Hashcode = 0;
for (let i = 0; i < str.length; i++) {
Hashcode = 37 * Hashcode + str.charCodeAt(i);
}
return Hashcode % size;
}
//放入数据
HashTable.prototype.put = function (key,val){
let index = HashFunc(key, this.size)
let bucket = this.table[index];
if (bucket == null){
bucket = [];
this.table[index] = bucket;
}
for (let j = 0; j < bucket.length; j++) {
let tuple = bucket[j];
if (tuple[0] === key){
tuple[1] = val;
return;
}
}
bucket.push([key,val]);
this.count += 1;
if (this.count > this.size * 0.75){
this.resize(this.getPrime(this.size *2));
}
}
//获取数据
HashTable.prototype.get = function (key){
let index = HashFunc(key,this.size);
let bucket = this.table[index];
if (bucket == null) return null;
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 = HashFunc(key,this.size);
let bucket = this.table[index];
if (bucket == null) return false;
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.size > 7 && this.count < this.size * 0.25 ){
this.resize(this.getPrime(Math.floor(this.size / 2)));
}
return true;
}
}
return false;
}
//是否为空
HashTable.prototype.isEmpty = function (){
return this.count === 0 ;
}
//元素数量
HashTable.prototype.getsize = function (){
return this.count;
}
//hash表扩容
HashTable.prototype.resize = function (newSize){
/**
* 扩容条件
* 1、装载因子(元素数量 / hash表长度) < 0.25 时缩容
* 2、装载因子(元素数量 / hash表长度) > 0.75 时扩容
* */
this.size = newSize;
let tem = [];
for (let i = 0; i <this.table.length; i++) {
let bucket = this.table[i];
if(bucket == null) continue;
for (let j = 0; j < bucket.length; j++) {
tem.push(bucket[j]);
}
}
this.table = [];
this.count = 0;
for (let i = 0; i < tem.length; i++) {
this.put(tem[i][0],tem[i][1]);
}
return this.count;
}
HashTable.prototype.getPrime = function (num){
while (!this.isPrime(num)){
num++;
}
return num;
}
HashTable.prototype.isPrime = function (num){
for (let i = 2; i <= parseInt(Math.sqrt(num));i++) {
if (num % i === 0){
return false;
}
}
return true;
}
}
let has = new HashTable();
// console.log(has.get("wcc"));
// console.log(has.get("cjt"));
// console.log(has.remove('yxh'))
// console.log(has.get("yxh"));
// console.log(has.get("666"));
has.put('yxh',{age:50})
has.put('cjt',{age:56})
has.put('wcc',{age:35})
has.put('wcc',{age:35})
has.put('cwc',{age:35})
has.put('ccw',{age:35})
has.put('sfhsajkfh',{age:666})
has.put('sfsafisuiof',{age:999})
console.log(has.table,has.size)