1 var baseRandom = require('../internal/baseRandom'),
2 isIterateeCall = require('../internal/isIterateeCall'),
3 toArray = require('../lang/toArray'),
4 toIterable = require('../internal/toIterable');
6 /* Native method references for those with the same name as other `lodash` methods. */
7 var nativeMin = Math.min;
10 * Gets a random element or `n` random elements from a collection.
14 * @category Collection
15 * @param {Array|Object|string} collection The collection to sample.
16 * @param {number} [n] The number of elements to sample.
17 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18 * @returns {*} Returns the random sample(s).
21 * _.sample([1, 2, 3, 4]);
24 * _.sample([1, 2, 3, 4], 2);
27 function sample(collection, n, guard) {
28 if (guard ? isIterateeCall(collection, n, guard) : n == null) {
29 collection = toIterable(collection);
30 var length = collection.length;
31 return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
34 result = toArray(collection),
35 length = result.length,
36 lastIndex = length - 1;
38 n = nativeMin(n < 0 ? 0 : (+n || 0), length);
40 var rand = baseRandom(index, lastIndex),
43 result[rand] = result[index];
44 result[index] = value;
50 module.exports = sample;