UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

62 lines (61 loc) 1.95 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sampleSize = void 0; const copyArray_1 = __importDefault(require("./.internal/copyArray")); const shuffleSelf_1 = __importDefault(require("./.internal/shuffleSelf")); const baseClamp_1 = __importDefault(require("./.internal/baseClamp")); const toInteger_1 = __importDefault(require("./toInteger")); const isArray_1 = __importDefault(require("./isArray")); const values_1 = __importDefault(require("./values")); const isIterateeCall_1 = __importDefault(require("./.internal/isIterateeCall")); /** * @ignore * @param array * @param n */ function arraySampleSize(array, n) { return (0, shuffleSelf_1.default)((0, copyArray_1.default)(array), (0, baseClamp_1.default)(n, 0, array.length)); } /** * @ignore * @param collection * @param n */ function baseSampleSize(collection, n) { const array = (0, values_1.default)(collection); return (0, shuffleSelf_1.default)(array, (0, baseClamp_1.default)(n, 0, array.length)); } /** * Gets `n` random elements at unique keys from `array` up to the * size of `array`. * * @since 5.11.0 * @category Array * @param collection The array to sample. * @param n The number of elements to sample. * @returns Returns the random elements. * @example * * ```js * sampleSize([1, 2, 3], 2) * // => [3, 1] * * sampleSize([1, 2, 3], 4) * // => [2, 3, 1] * ``` */ function sampleSize(collection, n = 1, guard) { if ((guard ? (0, isIterateeCall_1.default)(collection, n, guard) : n === undefined)) { n = 1; } else { n = (0, toInteger_1.default)(n); } const func = (0, isArray_1.default)(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } exports.sampleSize = sampleSize; exports.default = sampleSize;