From 305e30357c2aa29ef82404028bfdbd31f267f49e Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Sun, 29 Jul 2018 08:28:03 +0300 Subject: [PATCH] Add comments to HashTable hash function. --- src/data-structures/hash-table/HashTable.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/data-structures/hash-table/HashTable.js b/src/data-structures/hash-table/HashTable.js index 51575f98..1ae63a7f 100644 --- a/src/data-structures/hash-table/HashTable.js +++ b/src/data-structures/hash-table/HashTable.js @@ -25,6 +25,16 @@ export default class HashTable { * @return {number} */ hash(key) { + // For simplicity reasons we will just use character codes sum of all characters of the key + // to calculate the hash. + // + // But you may also use more sophisticated approaches like polynomial string hash to reduce the + // number of collisions: + // + // hash = charCodeAt(0) * PRIME^(n-1) + charCodeAt(1) * PRIME^(n-2) + ... + charCodeAt(n-1) + // + // where charCodeAt(i) is the i-th character code of the key, n is the length of the key and + // PRIME is just any prime number like 31. const hash = Array.from(key).reduce( (hashAccumulator, keySymbol) => (hashAccumulator + keySymbol.charCodeAt(0)), 0,