Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var baseRandom = require('../internal/baseRandom'),
2
isIterateeCall = require('../internal/isIterateeCall'),
3
toArray = require('../lang/toArray'),
4
toIterable = require('../internal/toIterable');
5
6
/* Native method references for those with the same name as other `lodash` methods. */
7
var nativeMin = Math.min;
8
9
/**
10
* Gets a random element or `n` random elements from a collection.
11
*
12
* @static
13
* @memberOf _
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).
19
* @example
20
*
21
* _.sample([1, 2, 3, 4]);
22
* // => 2
23
*
24
* _.sample([1, 2, 3, 4], 2);
25
* // => [3, 1]
26
*/
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;
32
}
33
var index = -1,
34
result = toArray(collection),
35
length = result.length,
36
lastIndex = length - 1;
37
38
n = nativeMin(n < 0 ? 0 : (+n || 0), length);
39
while (++index < n) {
40
var rand = baseRandom(index, lastIndex),
41
value = result[rand];
42
43
result[rand] = result[index];
44
result[index] = value;
45
}
46
result.length = n;
47
return result;
48
}
49
50
module.exports = sample;
51
52