This commit is contained in:
Chris Wanstrath 2025-09-28 22:56:59 -07:00
parent a8610f7e27
commit ef3909ef3d
2 changed files with 22 additions and 0 deletions

View File

@ -11,6 +11,8 @@ export function randomId(): string {
// rng(1, 5) #=> result can be 1 2 3 4 or 5
// rng(2) #=> result can be 1 or 2
export function rng(min: number, max = 0) {
if (min === 0 && max === 0) return 0
if (max === 0) {
max = min
min = 1

20
app/test/rng.test.ts Normal file
View File

@ -0,0 +1,20 @@
import { test } from "bun:test"
import { equal as assertEqual, ok as assert } from "assert"
import { rng, randomIndex } from "../src/shared/utils"
test("randomIndex", () => {
let idx = randomIndex([5, 7, 9])!
assert(idx >= 0 && idx < 3)
idx = randomIndex([5])!
assertEqual(idx, 0)
})
test("rng", () => {
assertEqual(rng(0, 0), 0)
const samples = Array.from({ length: 1000 }, () => rng(0, 1))
const avg = samples.reduce((a, b) => a + b, 0) / samples.length
assert(avg > 0.45 && avg < 0.55, "Average not close to 0.5")
})