mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 23:21:18 +08:00
Add comments to HashTable hash function.
This commit is contained in:
parent
f1152bf4b4
commit
305e30357c
@ -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,
|
||||||
|
Loading…
Reference in New Issue
Block a user