|
2 | 2 | const LinkedList = require('../../linked-lists/linked-list'); |
3 | 3 | const { nextPrime } = require('./primes'); |
4 | 4 |
|
| 5 | +// Text encoding |
| 6 | +const encoding = new TextEncoder(); |
| 7 | + |
5 | 8 | /** |
6 | 9 | * The map holds key-value pairs. |
7 | 10 | * Any value (both objects and primitive values) may be used as either a key or a value. |
@@ -50,12 +53,16 @@ class HashMap { |
50 | 53 | * @return {integer} bucket index |
51 | 54 | */ |
52 | 55 | hashFunction(key) { |
53 | | - const str = String(key); |
| 56 | + const bytes = encoding.encode(key); |
| 57 | + const { length } = bytes; |
| 58 | + |
54 | 59 | 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 |
57 | 63 | hash *= 16777619; // 32 bit FNV_prime |
58 | 64 | } |
| 65 | + |
59 | 66 | return (hash >>> 0) % this.buckets.length; |
60 | 67 | } |
61 | 68 | // end::hashFunction[] |
|
0 commit comments