UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

24 lines (22 loc) 513 B
import { dfdlT } from "@monstermann/dfdl"; //#region src/array/randomOr.ts /** * `randomOr(array, fallback)` * * Returns a random element from `array`, or `fallback` if the array is empty. * * ```ts * randomOr([1, 2, 3, 4], 0); // 2 (random) * ``` * * ```ts * pipe([1, 2, 3, 4], randomOr(0)); // 2 (random) * ``` */ const randomOr = dfdlT((target, or) => { if (target.length === 0) return or; const idx = Math.floor(Math.random() * target.length); return target[idx]; }, 2); //#endregion export { randomOr };