Created
July 20, 2018 04:47
-
-
Save jaredru/e66ae5ba3fc01b90fd1fc8fb1466fca5 to your computer and use it in GitHub Desktop.
JavaScript Consistent Hash
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
function makeLinearCongruentialGenerator(seed) { | |
const m = Math.pow(2, 31) - 1; | |
const a = 16807; | |
const c = 0; | |
let z = seed; | |
return function lcg() { | |
z = (a * z + c) % m; | |
return z / m; | |
} | |
} | |
export default function consistentHash(value, buckets) { | |
const lcg = makeLinearCongruentialGenerator(value); | |
let prev; | |
let next = 0; | |
do { | |
prev = next; | |
next = Math.floor((prev + 1) / lcg()); | |
} while (next < buckets); | |
return prev; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment