HashTable

98 阅读1分钟

js HashTable

class HashTable{
  constructor(size){
    this.data = new Array(size);
  }
  //es6,私有方法,不可访问 
  _hash(key){
    /*1,将字符串转换成比较大的数字:hash,
    2,将数字大的hash压缩到数组的(大小)范围内*/
    let hash = 0;
    //charCodeAt() returns an integer between 0 and
    // 65535 representing the UTF-16 code unit at the given index
    for(let i = 0;i<key.length;i++){
      hash = (hash + key.charCodeAt(i)*i)%this.data.length
    }
    //console.log(hash)
    return hash;
  }
  /*1.根据key值获取引用值
  2.判断当前位置是否存在,不存在就创建
  3.将传入的key,value添加到地址上
  */
  set(key,value){
    const address = this._hash(key);
    if(!this.data[address]){
      this.data[address] = [];
    }
    this.data[address].push([key,value]);
    return this.data;
    //console.log(this.data)
  }
  /*1.根据key值获取当前index
  2.根据获取的index获取到this.data中的bucket
  3.判断获取到的bucket是否存在,不存在返回undefined
  4.存在,遍历bucket中的每一个key值,找到传入的key,拿到value
   */
  get(key){
    const address = this._hash(key);
    const currentBucket = this.data[address];
    if(currentBucket){
      for(let i = 0;i < currentBucket.length;i++){
        if(currentBucket[i][0]===key){
          return currentBucket[i][1]
        }
      }
    }
    return undefined
  }
  /* 遍历或循环哈希表的所有键key
  */
  keys(){
    const keysArray = [];
    for(let i=0; i<this.data.length; i++){
      if(this.data[i]){
        keysArray.push(this.data[i][0][0]);
      }
    }
    return keysArray;
  }

}

const myHashTable = new HashTable(50);
/*
   myHashTable._hash('grapes');  //23
   console.log(hash);
   结果:
   0
   14
   8
   44
   48
   23
 => 23  
*/
myHashTable.set('grapes',66);
myHashTable.set('apples',456);
myHashTable.set('orange',111);
myHashTable.get('grapes');
console.log(myHashTable.keys());