Last active
June 23, 2021 09:37
-
-
Save Munawwar/e63e7ec8cce88806d3426af8c8777f6d to your computer and use it in GitHub Desktop.
randomlyDistributedHash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Deprecated: Dont use this. Just use fnv1a hash | |
function randomlyDistributedHash(s) { | |
// fnv1a hash | |
var h = 0x811c9dc5; | |
for (var i = 0, l = s.length; i < l; i++) { | |
h ^= s.charCodeAt(i); | |
h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24); | |
} | |
h = (h >>> 0); | |
// testing whether a Pseudo random number generator would give more uniform distribution | |
// than using fnv1a hash alone. | |
// Park-Miller-Carta Pseudo-Random Number Generator | |
var seed = h; // use fnv1a hash as seed | |
seed = seed % 2147483647; | |
if (seed <= 0) num += 2147483646; | |
return seed * 16807 % 2147483647; | |
} | |
// Usage with example: Distributing customers to servers | |
// var servers = ['server1', 'server2', 'server3']; | |
// console.log( | |
// 'server to use for customer =', | |
// servers[ randomlyDistributedHash('sessionIDOfCustomer') % servers.length ] | |
// ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My initial test was wrong. Seems like fnv1a has better bucket distribution.
Testing method:
I tried mapping the first 1 million number (converted to string) mapped into 10 buckets. Sequential data is useful for test as it would test how a single character change would affect distribution. A perfect hash would map exactly 1m/10 entries to each bucket. So for each bucket I counted hits / 1m (* 100 for percentage). Looks like fnv1a has lower average and max deviation from the ideal number.