Skip to content

Better hash function #56

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 20, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/data-structures/maps/hash-maps/hash-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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[]
Expand Down