Created
January 4, 2016 19:25
-
-
Save jhurliman/ad598b25721f745403e9 to your computer and use it in GitHub Desktop.
Demonstration of uniformly allocating integers into a fixed number of hash buckets
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
import * as math from 'mathjs' | |
const MINUTES_PER_DAY = 1440 | |
const REFRESH_MINUTES = 1 | |
const HASH_BUCKETS = MINUTES_PER_DAY / REFRESH_MINUTES | |
const MAX_IDS = 291554 | |
main() | |
function main () { | |
let buckets = new Array(HASH_BUCKETS) | |
for (let i = 0; i < HASH_BUCKETS; i++) { | |
buckets[i] = [] | |
} | |
for (let i = 0; i < MAX_IDS; i++) { | |
const bucket = jenkinsHash(i, HASH_BUCKETS) | |
buckets[bucket].push(i) | |
} | |
var counts = [] | |
for (let i = 0; i < HASH_BUCKETS; i++) { | |
counts.push(buckets[i].length) | |
} | |
console.log(`mean=${math.mean(counts)}, std=${math.std(counts)}, min=${math.min(counts)}, max=${math.max(counts)}`) | |
} | |
function jenkinsHash (key, intervalSize) { | |
key = '' + key | |
let hash = 0 | |
for (let i = 0; i < key.length; ++i) { | |
hash += key.charCodeAt(i) | |
hash += (hash << 10) | |
hash ^= (hash >> 6) | |
} | |
hash += (hash << 3) | |
hash ^= (hash >> 11) | |
hash += (hash << 15) | |
// Make unsigned and modulo intervalSize | |
return (hash >>> 0) % intervalSize | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment