diff --git a/src/data-structures/maps/hash-maps/hash-map.js b/src/data-structures/maps/hash-maps/hash-map.js index 0ce606ed..25889587 100644 --- a/src/data-structures/maps/hash-maps/hash-map.js +++ b/src/data-structures/maps/hash-maps/hash-map.js @@ -2,6 +2,9 @@ const LinkedList = require('../../linked-lists/linked-list'); const { nextPrime } = require('./primes'); +// Text encoding +const encoding = new TextEncoder(); + /** * The map holds key-value pairs. * Any value (both objects and primitive values) may be used as either a key or a value. @@ -50,12 +53,16 @@ class HashMap { * @return {integer} bucket index */ hashFunction(key) { - const str = String(key); + const bytes = encoding.encode(key); + const { length } = bytes; + let hash = 2166136261; // FNV_offset_basis (32 bit) - for (let i = 0; i < str.length; i += 1) { - hash ^= str.codePointAt(i); // XOR + + for (let i = 0; i < length; ) { + hash ^= bytes[i++]; // XOR hash *= 16777619; // 32 bit FNV_prime } + return (hash >>> 0) % this.buckets.length; } // end::hashFunction[]