UNPKG

1.27 kBJavaScriptView Raw
1import baseClamp from './_baseClamp';
2import baseRandom from './_baseRandom';
3import isIterateeCall from './_isIterateeCall';
4import toArray from './toArray';
5import toInteger from './toInteger';
6
7/**
8 * Gets `n` random elements at unique keys from `collection` up to the
9 * size of `collection`.
10 *
11 * @static
12 * @memberOf _
13 * @since 4.0.0
14 * @category Collection
15 * @param {Array|Object} collection The collection to sample.
16 * @param {number} [n=1] The number of elements to sample.
17 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
18 * @returns {Array} Returns the random elements.
19 * @example
20 *
21 * _.sampleSize([1, 2, 3], 2);
22 * // => [3, 1]
23 *
24 * _.sampleSize([1, 2, 3], 4);
25 * // => [2, 3, 1]
26 */
27function sampleSize(collection, n, guard) {
28 var index = -1,
29 result = toArray(collection),
30 length = result.length,
31 lastIndex = length - 1;
32
33 if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
34 n = 1;
35 } else {
36 n = baseClamp(toInteger(n), 0, length);
37 }
38 while (++index < n) {
39 var rand = baseRandom(index, lastIndex),
40 value = result[rand];
41
42 result[rand] = result[index];
43 result[index] = value;
44 }
45 result.length = n;
46 return result;
47}
48
49export default sampleSize;