Skip to content

Commit 4ec98b8

Browse files
authored
refactor(mobile): guard empty pool in pickRandom and parameterise its test
Address review feedback: - Throw on an empty pool so the `T` return type is honoured at runtime. - Convert the index-to-element test to an `it.each` table per repo preference. Generated-By: PostHog Code Task-Id: cddb89a6-66c3-4e63-b386-f8eb0394865f
1 parent 029ccf9 commit 4ec98b8

2 files changed

Lines changed: 12 additions & 6 deletions

File tree

apps/mobile/src/lib/pickRandom.test.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,15 @@ describe("pickRandom", () => {
1313
}
1414
});
1515

16-
it("draws a fresh pick from the random value on each call", () => {
17-
const pool = ["a", "b", "c", "d"];
18-
vi.spyOn(Math, "random").mockReturnValueOnce(0).mockReturnValueOnce(0.99);
19-
expect(pickRandom(pool)).toBe("a");
20-
expect(pickRandom(pool)).toBe("d");
21-
});
16+
it.each([
17+
{ randomValue: 0, expected: "a" },
18+
{ randomValue: 0.99, expected: "d" },
19+
])(
20+
"returns $expected when Math.random returns $randomValue",
21+
({ randomValue, expected }) => {
22+
const pool = ["a", "b", "c", "d"];
23+
vi.spyOn(Math, "random").mockReturnValueOnce(randomValue);
24+
expect(pickRandom(pool)).toBe(expected);
25+
},
26+
);
2227
});

apps/mobile/src/lib/pickRandom.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export function pickRandom<T>(pool: readonly T[]): T {
2+
if (pool.length === 0) throw new Error("pickRandom: pool must not be empty");
23
return pool[Math.floor(Math.random() * pool.length)];
34
}

0 commit comments

Comments
 (0)