Skip to content

Instantly share code, notes, and snippets.

@jaredru
Created July 20, 2018 04:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredru/e66ae5ba3fc01b90fd1fc8fb1466fca5 to your computer and use it in GitHub Desktop.
Save jaredru/e66ae5ba3fc01b90fd1fc8fb1466fca5 to your computer and use it in GitHub Desktop.
JavaScript Consistent Hash
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