@monstermann/fn
Version:
A utility library for TypeScript.
27 lines (25 loc) • 643 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
//#region src/array/randomOrElse.ts
/**
* `randomOrElse(array, callback)`
*
* Returns a random element from `array`, or the result of calling `callback` with the array if the array is empty.
*
* ```ts
* randomOrElse([1, 2, 3, 4], (arr) => arr.length); // 2 (random)
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* randomOrElse((arr) => arr.length),
* ); // 2 (random)
* ```
*/
const randomOrElse = dfdlT((target, orElse) => {
if (target.length === 0) return orElse(target);
const idx = Math.floor(Math.random() * target.length);
return target[idx];
}, 2);
//#endregion
export { randomOrElse };