Files
suaveplan/packages/foundation/random/pseudo-random/src/utils/sample.extra.test.ts
2026-05-27 23:47:53 +01:00

27 lines
854 B
TypeScript

import { describe, expect, it } from "@suaveplan/testing/runner";
import type { Rng } from "@suaveplan/types";
import { weightedChoice } from "./sample.js";
class FakeFloatRng implements Rng {
public constructor(protected value: number) {}
public nextUint32(): number {
return 0;
}
public nextFloat(): number {
return this.value;
}
}
describe("weightedChoice floating-point fallback", () => {
it("returns last index when target >= total (FP edge)", {
timeout: 5000,
}, () => {
// A nextFloat value of exactly 1 would make target === total,
// so `target < acc` never fires and the function must fall through
// to the defensive final return.
const rng = new FakeFloatRng(1);
const idx = weightedChoice([1, 2, 3], rng);
expect(idx).toBe(2);
});
});