947a28dc176c051b8b151cbe4054a5afe9d9a499
[yaffs-website] / node_modules / uncss / node_modules / lodash / sampleSize.js
1 var baseClamp = require('./internal/baseClamp'),
2     baseRandom = require('./internal/baseRandom'),
3     toArray = require('./toArray'),
4     toInteger = require('./toInteger');
5
6 /**
7  * Gets `n` random elements at unique keys from `collection` up to the
8  * size of `collection`.
9  *
10  * @static
11  * @memberOf _
12  * @category Collection
13  * @param {Array|Object} collection The collection to sample.
14  * @param {number} [n=0] The number of elements to sample.
15  * @returns {Array} Returns the random elements.
16  * @example
17  *
18  * _.sampleSize([1, 2, 3], 2);
19  * // => [3, 1]
20  *
21  * _.sampleSize([1, 2, 3], 4);
22  * // => [2, 3, 1]
23  */
24 function sampleSize(collection, n) {
25   var index = -1,
26       result = toArray(collection),
27       length = result.length,
28       lastIndex = length - 1;
29
30   n = baseClamp(toInteger(n), 0, length);
31   while (++index < n) {
32     var rand = baseRandom(index, lastIndex),
33         value = result[rand];
34
35     result[rand] = result[index];
36     result[index] = value;
37   }
38   result.length = n;
39   return result;
40 }
41
42 module.exports = sampleSize;