function simpleHash(key: string): number {
let sum = 0;
for (let i = 0; i < key.length; i++) {
sum += key.charCodeAt(i);
}
return sum % 10;
}
console.log(simpleHash('abc'));The ASCII codes are: 'a' = 97, 'b' = 98, 'c' = 99. Sum is 97 + 98 + 99 = 294. 294 % 10 = 4.
const hashTable: number[][] = [[], [], [], [], []];
function hash(key: number): number {
return key % 5;
}
const keys = [12, 7, 22, 17, 5];
for (const key of keys) {
hashTable[hash(key)].push(key);
}
console.log(hashTable);12 % 5 = 2 → bucket 2: [12]
7 % 5 = 2 → bucket 2: [12, 7]
22 % 5 = 2 → bucket 2: [12, 7, 22]
17 % 5 = 2 → bucket 2: [12, 7, 22, 17]
5 % 5 = 0 → bucket 0: [5]
Final state: [[5], [], [12, 7, 22, 17], [], []]
function hash(key: string): number {
let hashValue = 0;
for (let i = 0; i < key.length; i++) {
hashValue += key.charCodeAt(i);
}
return hashValue % 10;
}
console.log(hash('test'));The loop runs from i = 0 to i <= key.length, which means it tries to access key.charCodeAt(key.length), which is undefined.
Calling charCodeAt on undefined causes a TypeError.
A good hash function must always produce the same output for the same input (deterministic), distribute keys uniformly to avoid collisions, and be fast.
It does NOT need to be reversible; in fact, reversibility is not required and often not possible.
const size = 7; const table: (number | null)[] = Array(size).fill(null); function hash(key: number): number { return key % size; } function insert(key: number) { let idx = hash(key); while (table[idx] !== null) { idx = (idx + 1) % size; } table[idx] = key; } [10, 20, 15, 7, 32].forEach(insert); console.log(table);
Insert 10: 10%7=3 → table[3]=10. Table: [n,n,n,10,n,n,n]
Insert 20: 20%7=6 → table[6]=20. [n,n,n,10,n,n,20]
Insert 15: 15%7=1 → table[1]=15. [n,15,n,10,n,n,20]
Insert 7: 7%7=0 → table[0]=7. [7,15,n,10,n,n,20]
Insert 32: 32%7=4 → table[4]=32. [7,15,n,10,32,n,20]
Final: [7, 15, null, 10, 32, null, 20]
