Understanding and Using Hash Tables in JavaScript

Lesson Overview

Welcome to this lesson that aims to introduce Hash Tables and Hash Maps, a fundamental concept in data structures and algorithms. Hash tables, also known as Hash Maps in JavaScript, are extremely useful constructs that can drastically reduce time complexity while solving certain types of algorithmic problems. They provide an efficient way to maintain a collection of key-value pairs and allow quick access, insertion, and removal operations, making them highly effective in situations where quick lookups are necessary.

The Hashing Function

A key component of a hash map is the hashing function, which generates a hash value (usually an integer) from a given key. This hash value is used to determine where to store the associated value in the hash table. For integer keys, the hashing function simply returns the integer modulo the size of the hash table. However, keys can also be floats, strings, or other immutable types.

  • Floats: Floats can be converted to integers using techniques such as multiplying the float by a large constant and truncating the result. The chosen technique ensures that floats don't hash to the same value as their integer counterparts.
  • Strings: Strings are usually hashed by converting each character to its character code, then combining these codes in various ways—such as summing them or using polynomial accumulation. Given the variability in string lengths and characters, this helps distribute the hash values more uniformly.

Hash maps usually have a limited space, defined by the initial size of the hash table. While ideally, the hashing function should be a one-to-one function (injective), in practice it never is due to limited space and the infinite nature of potential input values. This results in collisions, where two different keys generate the same hash value. Hash maps typically handle collisions through various methods like chaining (using linked lists) or open addressing (linear probing, quadratic probing, etc.).

Have a look at the code snippets below, showcasing a simple example of hashing function implementations for integers, floats, and strings.

JavaScript
// For integer keys, the hashing function returns the integer modulo the size of the hash table.
function hashFunction(key, tableSize) {
  return key % tableSize;
}

// Hashing functions for float keys can convert them to integers.
function hashFloatKey(key, tableSize) {
  return Math.floor(key * 1000) % tableSize; // example
}

// Strings can be hashed by converting each character to its character code.
function hashStringKey(key, tableSize) {
  let hash = 0;
  for (let i = 0; i < key.length; i++) {
    hash += key.charCodeAt(i);
  }
  return hash % tableSize;
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal