educative.io

Mastering-data-structures-and-sorting-algorithms-in-javascript - Hash Table (Implementation)

The lesson for Hash Table implementation is wrong.

And in this instruction you never increase the size, yet you use the size to create hash, which will always give you NaN. Since you can’t MOD int with 0. It will always give you NaN.

Here is the class:

class HashTable {
  constructor() {
    this.values = {};
    this.length = 0;
    this.size = 0;
  }

  calculateHash(key) {
    return key.toString().length % this.size;
  }

  add(key, value) {
    const hash = this.calculateHash(key);
    if (!this.values.hasOwnProperty(hash)) {
      this.values[hash] = {};
    }
    if (!this.values[hash].hasOwnProperty(key)) {
      this.length++;
    }
    this.values[hash][key] = value;
  }

  search(key) {
    const hash = this.calculateHash(key);
    if (this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) {
      return this.values[hash][key];
    } else {
      return null;
    }
  }
}

Please fix this lesson.

1 Like

Has been more than half a year and no reply. What gives?