Skip to content

Commit

Permalink
Merge pull request #56 from nuintun/patch-1
Browse files Browse the repository at this point in the history
feat(hashmap): Better hash function using TextEncoder

Improves hash function using TextEncoder instead of codePointAt

Closes #55
  • Loading branch information
amejiarosario committed May 20, 2020
2 parents 142c301 + c253938 commit 6974354
Showing 1 changed file with 10 additions and 3 deletions.
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

0 comments on commit 6974354

Please sign in to comment.