aashish578

Aashish Panchal

Posted on October 27, 2020

Hash Tables
class HashTable {
  constructor(size=53){
    this.keyMap = new Array(size);
  }

  _hash(key) {
    let total = 0;
    let WEIRD_PRIME = 31;
    for (let i = 0; i < Math.min(key.length, 100); i++) {
      let char = key[i];
      let value = char.charCodeAt(0) - 96
      total = (total * WEIRD_PRIME + value) % this.keyMap.length;
    }
    return total;
  }

  // Add a Value
  set(key, value) {
    let index = this._hash(key);
    if(!this.keyMap[index]) {
      this.keyMap[index] = [];
    }
    this.keyMap[index].push([key, value]);
    console.log(` ${key} or ${value} ->> is added successfully πŸ‘πŸ‘`)
    return ht;
  }

  // Find a value 
  get(key) {
    let index = this._hash(key);
    if(this.keyMap[index]) {
      for(let i = 0; i < this.keyMap[index].length; i++) {
        if(this.keyMap[index][i][0] === key) {
          return this.keyMap[index][i][1]
        }
      }
    }
    return undefined;
  }

  // Show all Keys
  keys() {
    let keysArr = [];
    for(let i = 0; i <this.keyMap.length; i++) {
      if(this.keyMap[i]) {
        for( let j = 0; j < this.keyMap[i].length; j++) {
          if(!keysArr.includes(this.keyMap[i][j][0])) { 
            keysArr.push(this.keyMap[i][j][0])
          }
        }
      }
    }
    console.log(` Your Keys is -> ${keysArr}`);
    return keysArr;
  }

  // Show all Value
  value() {
    let valuesArr = [];
    for(let i = 0; i <this.keyMap.length; i++) {
      if(this.keyMap[i]) {
        for( let j = 0; j < this.keyMap[i].length; j++) {
          if(!valuesArr.includes(this.keyMap[i][j][1])) { 
            valuesArr.push(this.keyMap[i][j][1])
          }
        }
      }
    }
    console.log(` Your Value is -> ${valuesArr}`)
    return valuesArr;
  }
}

let ht = new HashTable(17);
ht.set("java script ", "java")
ht.set("html ", "css")
ht.set("c ", "c++")
ht.value();
ht.keys();



//  ht.keys().forEach(function(key) {
//    console.log(` -> your Key is -> ${ht.get(key)}`);
//  })

//       πŸ‘†πŸ‘† πŸ‘† πŸ‘† πŸ‘† πŸ‘† πŸ‘† πŸ‘† πŸ‘†

//           πŸ‘‰  OUTPUT πŸ‘ˆ

//            -> your Key is -> java
//            -> your Key is -> css 
//            -> your Key is -> c++
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
aashish578
Aashish Panchal

Posted on October 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related