@charpeni/one-of
Version:
Type-safe utilities to return a random element from an array or random entry from an object
18 lines (16 loc) • 424 B
JavaScript
//#region src/oneElementOf.ts
/**
* Returns one random element from the array.
*
* @example
* ```ts
* oneElementOf([1, 2, 3]); // 2
* ```
*/
function oneElementOf(array) {
if (!Array.isArray(array)) throw new TypeError("Expected an array");
if (array.length === 0) throw new Error("Expected a non-empty array");
return array[Math.floor(Math.random() * array.length)];
}
//#endregion
exports.oneElementOf = oneElementOf;