Skip to content
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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize numberHash.js #17074

Merged
merged 1 commit into from
Apr 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 17 additions & 27 deletions lib/util/numberHash.js
Original file line number Diff line number Diff line change
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;
}
};