draw
The draw utility picks a single random element from an array. It is perfect for sampling data, picking winners in a game, or selecting random items for display.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
import { IS_ARRAY_ERROR_MSG, isArray } from '../typed/isArray';
import { random } from './random';
/**
* “Draw” a random item from an array.
*
* @example
* ```ts
* draw([1, 2, 3]) // 3
* ```
*
* @param array - The array to draw from.
*
* @returns A random item from the array or `undefined` if the array is empty.
*
* @throws {TypeError} If the provided array is not an array.
*/
export const draw = <T>(array: T[]): T | undefined => {
assert(isArray(array), IS_ARRAY_ERROR_MSG, { args: { array }, type: TypeError });
if (array.length === 0) return undefined;
return array[random(0, array.length - 1)];
};Features
- Isomorphic: Works in both Browser and Node.js.
- Fair Selection: Uses a uniform distribution to ensure every element has an equal chance of being picked.
- Immutable: Does not modify the original array.
- Type-safe: Properly infers the return type based on the array elements.
API
ts
function draw<T>(array: T[]): T | undefined;Parameters
array: The array to draw from.
Returns
- A random element from the array.
- Returns
undefinedif the array is empty.
Examples
Basic Usage
ts
import { draw } from '@vielzeug/toolkit';
const fruits = ['apple', 'banana', 'cherry', 'date'];
const randomFruit = draw(fruits);
// returns one of the fruits randomlySampling Objects
ts
import { draw } from '@vielzeug/toolkit';
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
];
const winner = draw(users);
// returns one user objectImplementation Notes
- Internally leverages the
randomutility to generate an index between0andarray.length - 1. - Throws
TypeErrorif the input is not an array. - Performance is $O(1)$ as it only picks one index regardless of array size.