Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/core/sticky.test.ts
1542 views
1
import { consistentHashingChoice } from "./sticky";
2
3
describe("tests of consistentHashingChoice", () => {
4
it("throws when set has size 0", () => {
5
expect(() => consistentHashingChoice(new Set(), "x")).toThrow("size");
6
});
7
8
it("for size one it just returns the unique item", () => {
9
expect(consistentHashingChoice(new Set(["foo"]), "bar")).toEqual("foo");
10
});
11
12
it("for size 3 it gives the same result every time for the same input (and also that it's not stupidly slow)", () => {
13
const v = new Set(["a", "b", "x"]);
14
const resource = "thing";
15
const choice = consistentHashingChoice(v, resource);
16
expect(v.has(choice)).toBe(true);
17
for (let i = 0; i < 1000; i++) {
18
expect(consistentHashingChoice(v, resource)).toBe(choice);
19
}
20
});
21
22
it("the results are uniformly distributed when the resources are different", () => {
23
const v = new Set(["a", "b", "x"]);
24
const c = { a: 0, b: 0, x: 0 };
25
for (let i = 0; i < 1000; i++) {
26
c[consistentHashingChoice(v, `${i}`)] += 1;
27
}
28
// just roughly in the direction of uniform...
29
expect(c.a).toBeGreaterThan(250);
30
expect(c.b).toBeGreaterThan(250);
31
expect(c.x).toBeGreaterThan(250);
32
});
33
});
34
35