Quick actions

cmd+k|ctrl+k

Navigation

Languages

Implement a Hash Table

Snippet info

Language

JavaScript

Visibility

public

Author

gyanirocks

Created

2025-03-10T15:03:35.86056Z

Updated

2025-03-11T13:46:34.307925Z

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

// This is a simple hash function 
  _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, value) {
    let address = this._hash(key);
    if (!this.data[address]) {
      this.data[address] = [];
    }
    this.data[address].push([key, value]);
    console.log(this.data)
    return this.data;
  }

  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) {
          console.log(currentBucket[i][1])
          return currentBucket[i][1]
        }
      }
    }
    return undefined;
  }
  
  keys() {
      const keysArray = [];
      for (let i = 0; i < this.data.length; i++){
          if(this.data[i]){
              keysArray.push(this.data[i][0][0])
          }
      }
      console.log(keysArray);
  }
}

const myHashTable = new HashTable(50);
myHashTable.set('grapes', 10000)
myHashTable.get('grapes')
myHashTable.set('apples', 9)
myHashTable.get('apples')
myHashTable.set('oranges', 2)
myHashTable.get('oranges')
myHashTable.keys();
INFO