sample
collection
Gets a random element from collection.
Installation
Import
import { sample } from '@tulx/utils';Source Code
Implementation
/**
* Gets a random element from collection.
*
* @param collection - The collection to sample.
* @returns Returns the random element.
*
* @example
* ```ts
* sample([1, 2, 3, 4]); // 2 (random)
* ```
*/
export function sample<T>(
collection: readonly T[] | Record<string, T>
): T | undefined {
const items = Array.isArray(collection)
? collection
: Object.values(collection);
if (items.length === 0) {
return undefined;
}
const randomIndex = Math.floor(Math.random() * items.length);
return items[randomIndex];
}
Example
import { sample } from '@tulx/utils';
sample([1, 2, 3, 4]); // 2 (random)Related Functions
countBy
Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
each
Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).
eachRight
This method is like each except that it iterates over elements of collection from right to left.
every
Checks if predicate returns truthy for all elements of collection.
filter
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
find
Iterates over elements of collection, returning the first element predicate returns truthy for.