mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-03 00:27:50 +00:00
Bump to v4.0.0.
This commit is contained in:
38
sampleSize.js
Normal file
38
sampleSize.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import baseClamp from './internal/baseClamp';
|
||||
import baseRandom from './internal/baseRandom';
|
||||
import toArray from './toArray';
|
||||
import toInteger from './toInteger';
|
||||
|
||||
/**
|
||||
* Gets `n` random elements from `collection`.
|
||||
*
|
||||
* @static
|
||||
* @memberOf _
|
||||
* @category Collection
|
||||
* @param {Array|Object} collection The collection to sample.
|
||||
* @param {number} [n=0] The number of elements to sample.
|
||||
* @returns {Array} Returns the random elements.
|
||||
* @example
|
||||
*
|
||||
* _.sampleSize([1, 2, 3, 4], 2);
|
||||
* // => [3, 1]
|
||||
*/
|
||||
function sampleSize(collection, n) {
|
||||
var index = -1,
|
||||
result = toArray(collection),
|
||||
length = result.length,
|
||||
lastIndex = length - 1;
|
||||
|
||||
n = baseClamp(toInteger(n), 0, length);
|
||||
while (++index < n) {
|
||||
var rand = baseRandom(index, lastIndex),
|
||||
value = result[rand];
|
||||
|
||||
result[rand] = result[index];
|
||||
result[index] = value;
|
||||
}
|
||||
result.length = n;
|
||||
return result;
|
||||
}
|
||||
|
||||
export default sampleSize;
|
||||
Reference in New Issue
Block a user