Quick actions

cmd+k|ctrl+k

Navigation

Languages

HashTable

Snippet info

Language

JavaScript

Visibility

public

Author

kishorrathva8298

Created

2022-03-31T22:25:37.027928Z

Updated

2022-04-03T00:09:42.160836Z

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

  _hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      // O(1)
      hash = (hash + key.charCodeAt(i) * i) % this.data.length;
    }
    return hash;
  }

  set(key, value) {
    // this.data[this._hash(key)] = [key,value];
    let address = this._hash(key);
    if (!this.data[address]) {
      this.data[address] = [];
    }
    this.data[address].push([key, value]);
    // console.log(this.data);
  }
  get(key) {
    // return this.data[this._hash(key)];
    let address = this._hash(key);
    const currentBucket = this.data[address];
    if (currentBucket) {
      // Only incase of Hash Collisions
      for (let i = 0; i < currentBucket.length; i++) {
        if (currentBucket[i][0] === key) {
          return currentBucket[i][1];
        }
      }
    } // O(1)
    return undefined;
  }

  keys() {
    const keysArray = [];
    for (let i = 0; i < this.data.length; i++) { //O(n)
      if (this.data[i]) {
        if (this.data[i].length !== 1) {
            // This is worst case : Hash Collisions
          for (let j = 0; j < this.data[i].length; j++) { // O(m)
            keysArray.push(this.data[i][j][0]);
          }
          // O(n*m);
        } else {
          keysArray.push(this.data[i][0][0]); // O(n)
        }
      }
    }
    return keysArray;
  }
}

const myHashTable = new HashTable(2);
myHashTable.set("grapes", 100000);
myHashTable.set("apples", 54);
myHashTable.set("oranges", 2);
myHashTable.set("mangoes", 23);
// console.log(myHashTable.get("grapes"));
// console.log(myHashTable.get("apples"));
// console.log(myHashTable.get("oranges"));
// console.log(myHashTable.get("mangoes"));
console.log(myHashTable.keys());
INFO