UNPKG

diginext-utils

Version:
52 lines 1.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sample = sample; /** * Gets N random elements from an array. * If N is not specified or greater than array length, returns all elements shuffled. * * @template T - The type of elements in the array * @param array - The array to sample from * @param n - Number of elements to sample (optional) * @returns A new array with N random elements * * @example * ```ts * sample([1, 2, 3, 4, 5], 2); // Two random elements, e.g., [3, 1] * sample(['a', 'b', 'c']); // All elements in random order * sample([1, 2, 3], 5); // All elements in random order (n > length) * ``` */ function sample(array, n) { if (!Array.isArray(array) || array.length === 0) { return []; } const sampleSize = n !== undefined ? Math.min(n, array.length) : array.length; if (sampleSize >= array.length) { // Return shuffled copy of entire array const result = [...array]; for (let i = result.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = result[i]; result[i] = result[j]; result[j] = temp; } return result; } // Use Set to avoid duplicates when sampling const result = []; const taken = new Set(); const len = array.length; while (result.length < sampleSize) { const index = Math.floor(Math.random() * len); if (!taken.has(index)) { taken.add(index); const element = array[index]; if (element !== undefined) { result.push(element); } } } return result; } //# sourceMappingURL=sample.js.map