Skip to content

Build a hash map from an array

Deep diveBuild alongTypeScriptYou need: arrays and loops
What you’ll build: A string-keyed hash map built on a plain array, in six steps: a hash function, buckets, chaining, delete, resizing, and a test against Map.fn hash(key)8 buckets to startset set, get, has, delete0.75 load factor, then doubletest 10,000 ops against Map
Step 1 of 6

Turn a string into a number

Make a folder with a package.json that sets "type": "module", so Node treats your .ts files as ES modules.

hash.ts walks the key one character at a time: multiply the total by 31, add the character code. >>> 0 keeps the result a whole number from 0 to 2³² − 1.

WHY

A map needs one thing from a key: the same number every time you ask. cat gives 98262 on every run, and act, with the same letters, gives a different number because the order changes the sum. Java’s String.hashCode uses the same multiplier, 31.

package.jsonnew+5−0
Added: {
Added: "name": "hash-map",
Added: "private": true,
Added: "type": "module"
Added: }
hash.tsnew+8−0
Added: // Turns a string into a whole number from 0 to 2^32 - 1.
Added: export function hash(key: string): number {
Added: let h = 0;
Added: for (let i = 0; i < key.length; i++) {
Added: h = (h * 31 + key.charCodeAt(i)) >>> 0;
Added: }
Added: return h;
Added: }
demo.tsnew+5−0
Added: import { hash } from './hash.ts';
Added:
Added: for (const key of ['cat', 'act', 'dog', 'cat']) {
Added: console.log(key, hash(key));
Added: }