fix rng
This commit is contained in:
parent
a8610f7e27
commit
ef3909ef3d
|
|
@ -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
20
app/test/rng.test.ts
Normal 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")
|
||||
})
|
||||
|
||||
Loading…
Reference in New Issue
Block a user