File tree Expand file tree Collapse file tree 1 file changed +10
-3
lines changed
src/data-structures/maps/hash-maps Expand file tree Collapse file tree 1 file changed +10
-3
lines changed Original file line number Diff line number Diff line change 22const LinkedList = require ( '../../linked-lists/linked-list' ) ;
33const { nextPrime } = require ( './primes' ) ;
44
5+ // Text encoding
6+ const encoding = new TextEncoder ( ) ;
7+
58/**
69 * The map holds key-value pairs.
710 * Any value (both objects and primitive values) may be used as either a key or a value.
@@ -50,12 +53,16 @@ class HashMap {
5053 * @return {integer } bucket index
5154 */
5255 hashFunction ( key ) {
53- const str = String ( key ) ;
56+ const bytes = encoding . encode ( key ) ;
57+ const { length } = bytes ;
58+
5459 let hash = 2166136261 ; // FNV_offset_basis (32 bit)
55- for ( let i = 0 ; i < str . length ; i += 1 ) {
56- hash ^= str . codePointAt ( i ) ; // XOR
60+
61+ for ( let i = 0 ; i < length ; ) {
62+ hash ^= bytes [ i ++ ] ; // XOR
5763 hash *= 16777619 ; // 32 bit FNV_prime
5864 }
65+
5966 return ( hash >>> 0 ) % this . buckets . length ;
6067 }
6168 // end::hashFunction[]
You can’t perform that action at this time.
0 commit comments