Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c253938

Browse files
authored
Better hash function
1 parent 142c301 commit c253938

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

‎src/data-structures/maps/hash-maps/hash-map.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
const LinkedList = require('../../linked-lists/linked-list');
33
const { 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[]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /