Quick actions

cmd+k|ctrl+k

Navigation

Languages

Implementation of Hash Table

Snippet info

Language

JavaScript

Visibility

public

Author

dhamankovachi1

Created

2023-10-29T14:11:24.171605Z

Updated

2023-10-30T01:49:11.700945Z

class HashTable {
  constructor(size){
    this.data = new Array(size);
  }

  _hash(key) {
    let hash = 0;
    for (let i =0; i < key.length; i++){
        hash = (hash + key.charCodeAt(i) * i) % this.data.length
    }
    return hash;
  }
  set(key,values){
     let address=this._hash(key);
     if(!this.data[address]){
         this.data[address]=[];
     }
     this.data[address].push([key,values])
     return this.data
        
  }
  get(key){
      let 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
  }
  
  keys(){
      const keyArrays=[]
      for(let i=0;i<this.data.length;i++){
          if(this.data[i]){
              keyArrays.push(this.data[i][0][0])
          }
      }
      return keyArrays
  }
}

const myHashTable = new HashTable(50);
myHashTable.set('grapes', 10000)
myHashTable.set('apples',54)
myHashTable.keys()
INFO