import { getRandomUnitValue } from "./base.ts" // 默认 true 概率为 0.5。 // 当调用方未传入参数时,randomBoolean 会生成一个均匀分布的随机布尔值。 const internalDefaultRandomBooleanProbability = 0.5 // Step 1: 校验 true 概率。 // // randomBoolean 只接受 0 到 1 之间的有限数值,避免把无效概率带入比较逻辑。 const internalAssertRandomBooleanProbability = (value: number): void => { if (Number.isFinite(value) === false) { throw new TypeError(`Expected probability to be a finite number, got: ${value}`) } if (value < 0 || value > 1) { throw new RangeError(`Expected probability to be between 0 and 1 inclusive, got: ${value}`) } } /** * @description 生成随机布尔值,并可选指定返回 `true` 的概率。 * * 当未传入参数时,`true` 与 `false` 的概率各为一半;当传入 `probability` 时,会将其解释为返回 `true` 的概率,其中 `0` 表示恒为 `false`,`1` * 表示恒为 `true`。 * * @example * ``` * const sample1 = randomBoolean() * // Expect: true * const example1 = typeof sample1 === "boolean" * // Expect: false * const example2 = randomBoolean(0) * // Expect: true * const example3 = randomBoolean(1) * ``` */ export const randomBoolean = ( probability: number = internalDefaultRandomBooleanProbability, ): boolean => { internalAssertRandomBooleanProbability(probability) return getRandomUnitValue() < probability }