sampleSize
collection
Gets n random elements at unique keys from collection up to the size of collection.
Installation
Import
import { sampleSize } from '@tulx/utils';Source Code
Implementation
/**
* Gets n random elements at unique keys from collection up to the size of collection.
*
* @param collection - The collection to sample.
* @param n - The number of elements to sample.
* @returns Returns the random elements.
*
* @example
* ```ts
* sampleSize([1, 2, 3], 2); // [3, 1] (random)
* sampleSize([1, 2, 3], 4); // [1, 2, 3] (random)
* ```
*/
export function sampleSize<T>(
collection: readonly T[] | Record<string, T>,
n: number = 1
): T[] {
const items = Array.isArray(collection)
? [...collection]
: Object.values(collection);
const length = items.length;
const sampleCount = Math.min(n, length);
if (sampleCount === 0) {
return [];
}
const result: T[] = [];
const indices = new Set<number>();
while (indices.size < sampleCount) {
const randomIndex = Math.floor(Math.random() * length);
if (!indices.has(randomIndex)) {
indices.add(randomIndex);
result.push(items[randomIndex]);
}
}
return result;
}
Example
import { sampleSize } from '@tulx/utils';
sampleSize([1, 2, 3], 2); // [3, 1] (random)
sampleSize([1, 2, 3], 4); // [1, 2, 3] (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.