JCH - Jump Consistent Hash Library for Javascript in Deno.
A Fast, Minimal Memory, Consistent Hash Algorithm.
We present jump consistent hash, a fast, minimal memory, consistent hash algorithm that can be expressed in about 5 lines of code. In comparison to the algorithm of Karger et al., jump consistent hash requires no storage, is faster, and does a better job of evenly dividing the key space among the buckets and of evenly dividing the workload when the number of buckets changes. Its main limitation is that the buckets must be numbered sequentially, which makes it more suitable for data storage applications than for distributed web caching.
Paper: https://arxiv.org/abs/1406.2294
Usage
const a = ch(286293355577, 500000) // support TS type Number. Since all JS numbers are 64 bits floating number.
const b = ch("127.0.0.1", 1073741824) // currently not support type String yet. Maybe can port outputs to crc32 or bkdr in the future.or check example code located at ./ex/01.ts.
The algorithm works by using a hash of the key as the seed for a random number generator. It then uses the random numbers to βjump forwardβ in the list of buckets until it falls off the end. The last bucket it lands in is the result. The paper has a more complete explanation of how it works and a derivation of this optimized loop.
While evenly divide keys into buckets uniformly, we can change total bucket amount(add/remove buckets) but still remain the old key values as possible.
You may see results like this:
ββββββββββββββ¬ββββββ¬βββββββββ
β (iter idx) β Key β Values β
ββββββββββββββΌββββββΌβββββββββ€
β 0 β 1 β 7527 β
β 1 β 7 β 7392 β
β 2 β 4 β 7505 β
β 3 β 0 β 7523 β
β 4 β 3 β 7487 β
β 5 β 8 β 7683 β
β 6 β 2 β 7484 β
β 7 β 6 β 7510 β
β 8 β 5 β 7547 β
β 9 β 9 β 7342 β
ββββββββββββββ΄ββββββ΄βββββββββ
buckets after add two nodes:
ββββββββββββββ¬ββββββ¬βββββββββ
β (iter idx) β Key β Values β
ββββββββββββββΌββββββΌβββββββββ€
β 0 β 1 β 6275 β
β 1 β 7 β 6151 β
β 2 β 4 β 6249 β
β 3 β 0 β 6190 β
β 4 β 3 β 6226 β
β 5 β 8 β 6413 β
β 6 β 2 β 6251 β
β 7 β 6 β 6264 β
β 8 β 5 β 6325 β
β 9 β 9 β 6137 β
β 10 β 10 β 6140 β
β 11 β 11 β 6277 β
ββββββββββββββ΄ββββββ΄βββββββββJump Hash addresses the two disadvantages of ring hashes: it has no memory overhead and virtually perfect key distribution. (The standard deviation of buckets is 0.000000764%, giving a 99% confidence interval of 0.99999998 to1.00000002).
Jump Hash is also fast. The loop executes O(ln n) times, faster by a constant amount than the O(log n) binary search for Ring Hash, and made faster even still by the fact that the computation is done entirely in a few registers and doesnβt pay the overhead of cache misses.