Skip to content

Commit

Permalink
Merge pull request #17074 from alexkuz/patch-2
Browse files Browse the repository at this point in the history
Optimize numberHash.js
  • Loading branch information
TheLarkInn committed Apr 27, 2023
2 parents a3e7e4d + f952351 commit 3f9dc03
Showing 1 changed file with 17 additions and 27 deletions.
44 changes: 17 additions & 27 deletions lib/util/numberHash.js
Expand Up @@ -68,42 +68,32 @@ module.exports = (str, range) => {
for (let i = 0; i < str.length; i++) {
// Get the character code.
const c = str.charCodeAt(i);

// For each 32-bit integer used to store the hash value
for (let j = 0; j < COUNT; j++) {
// Get the index of the previous 32-bit integer.
const p = (j + COUNT - 1) % COUNT;
// Add the character code to the current hash value and multiply by the prime number.
arr[j] = (arr[j] + c * primes[j] + arr[p]) & SAFE_PART;
}
// add the character code to the current hash value and multiply by the prime number and
// add the previous 32-bit integer.
arr[0] = (arr[0] + c * primes[0] + arr[3]) & SAFE_PART;
arr[1] = (arr[1] + c * primes[1] + arr[0]) & SAFE_PART;
arr[2] = (arr[2] + c * primes[2] + arr[1]) & SAFE_PART;
arr[3] = (arr[3] + c * primes[3] + arr[2]) & SAFE_PART;

// For each 32-bit integer used to store the hash value
for (let j = 0; j < COUNT; j++) {
// Get the index of the next 32-bit integer.
const q = arr[j] % COUNT;
// XOR the current hash value with the value of the next 32-bit integer.
arr[j] = arr[j] ^ (arr[q] >> 1);
}
// XOR the current hash value with the value of the next 32-bit integer.
arr[0] = arr[0] ^ (arr[arr[0] % COUNT] >> 1);
arr[1] = arr[1] ^ (arr[arr[1] % COUNT] >> 1);
arr[2] = arr[2] ^ (arr[arr[2] % COUNT] >> 1);
arr[3] = arr[3] ^ (arr[arr[3] % COUNT] >> 1);
}

if (range <= SAFE_PART) {
let sum = 0;
// For each 32-bit integer used to store the hash value
for (let j = 0; j < COUNT; j++) {
// Add the value of the current 32-bit integer to the sum.
sum = (sum + arr[j]) % range;
}
return sum;
return (arr[0] + arr[1] + arr[2] + arr[3]) % range;
} else {
let sum1 = 0;
let sum2 = 0;
// Calculate the range extension.
const rangeExt = Math.floor(range / SAFE_LIMIT);
for (let j = 0; j < COUNT; j += 2) {
sum1 = (sum1 + arr[j]) & SAFE_PART;
}
for (let j = 1; j < COUNT; j += 2) {
sum2 = (sum2 + arr[j]) % rangeExt;
}

const sum1 = (arr[0] + arr[2]) & SAFE_PART;
const sum2 = (arr[0] + arr[2]) % rangeExt;

return (sum2 * SAFE_LIMIT + sum1) % range;
}
};

0 comments on commit 3f9dc03

Please sign in to comment.