react / wstein / node_modules / jest-cli / node_modules / istanbul / node_modules / js-yaml / node_modules / argparse / node_modules / lodash / collection / sample.js
80742 viewsvar baseRandom = require('../internal/baseRandom'),1isIterateeCall = require('../internal/isIterateeCall'),2toArray = require('../lang/toArray'),3toIterable = require('../internal/toIterable');45/* Native method references for those with the same name as other `lodash` methods. */6var nativeMin = Math.min;78/**9* Gets a random element or `n` random elements from a collection.10*11* @static12* @memberOf _13* @category Collection14* @param {Array|Object|string} collection The collection to sample.15* @param {number} [n] The number of elements to sample.16* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.17* @returns {*} Returns the random sample(s).18* @example19*20* _.sample([1, 2, 3, 4]);21* // => 222*23* _.sample([1, 2, 3, 4], 2);24* // => [3, 1]25*/26function sample(collection, n, guard) {27if (guard ? isIterateeCall(collection, n, guard) : n == null) {28collection = toIterable(collection);29var length = collection.length;30return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;31}32var index = -1,33result = toArray(collection),34length = result.length,35lastIndex = length - 1;3637n = nativeMin(n < 0 ? 0 : (+n || 0), length);38while (++index < n) {39var rand = baseRandom(index, lastIndex),40value = result[rand];4142result[rand] = result[index];43result[index] = value;44}45result.length = n;46return result;47}4849module.exports = sample;505152