- Understand a hash function
- Visualize collisions
- Separate average from worst case
From text to index
The hash function must be deterministic and distribute keys. Modulo fits the result into the bucket count.
function hash(key, size) {
let total = 0;
for (const char of key) total += char.charCodeAt(0);
return total % size;
}Two keys, one bucket
A collision is not an error; it is part of the design. Separate chaining stores a small collection per bucket; open addressing finds another position.
- More buckets reduce collisions and consume more memory.
- A poor function concentrates keys.
- Load factor tells you when to resize.
In products: use Map
Implementing a table teaches the concept. In JavaScript applications, Map already handles identity, growth, and collisions robustly.
Create a collision
With four buckets, find two words that end up at the same index using the example function.
Show a hint
Reorder letters: the simple sum has obvious limitations.