Add comments to HashTable hash function.

This commit is contained in:
Oleksii Trekhleb 2018-07-29 08:28:03 +03:00
parent f1152bf4b4
commit 305e30357c

View File

@ -25,6 +25,16 @@ export default class HashTable {
* @return {number} * @return {number}
*/ */
hash(key) { 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( const hash = Array.from(key).reduce(
(hashAccumulator, keySymbol) => (hashAccumulator + keySymbol.charCodeAt(0)), (hashAccumulator, keySymbol) => (hashAccumulator + keySymbol.charCodeAt(0)),
0, 0,