mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-04 08:57:49 +00:00
Simplify shuffle and sample.
This commit is contained in:
@@ -1,15 +1,13 @@
|
||||
import arraySampleSize from './.internal/arraySampleSize.js'
|
||||
import baseSampleSize from './.internal/baseSampleSize.js'
|
||||
import isIterateeCall from './.internal/isIterateeCall.js'
|
||||
import toInteger from './toInteger.js'
|
||||
|
||||
/**
|
||||
* Gets `n` random elements at unique keys from `collection` up to the
|
||||
* size of `collection`.
|
||||
* Gets `n` random elements at unique keys from `array` up to the
|
||||
* size of `array`.
|
||||
*
|
||||
* @since 4.0.0
|
||||
* @category Collection
|
||||
* @param {Array|Object} collection The collection to sample.
|
||||
* @category Array
|
||||
* @param {Array} array The array to sample.
|
||||
* @param {number} [n=1] The number of elements to sample.
|
||||
* @param- {Object} [guard] Enables use as an iteratee for methods like `map`.
|
||||
* @returns {Array} Returns the random elements.
|
||||
@@ -21,14 +19,27 @@ import toInteger from './toInteger.js'
|
||||
* sampleSize([1, 2, 3], 4)
|
||||
* // => [2, 3, 1]
|
||||
*/
|
||||
function sampleSize(collection, n, guard) {
|
||||
function sampleSize(array, n, guard) {
|
||||
if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
|
||||
n = 1
|
||||
} else {
|
||||
n = toInteger(n)
|
||||
}
|
||||
const func = Array.isArray(collection) ? arraySampleSize : baseSampleSize
|
||||
return func(collection, n)
|
||||
const length = array == null ? 0 : array.length
|
||||
if (!length || n < 1) {
|
||||
return []
|
||||
}
|
||||
n = n > length ? length : n
|
||||
let index = -1
|
||||
const lastIndex = n - 1
|
||||
const result = copyArray(array)
|
||||
while (++index < n) {
|
||||
const rand = index + Math.floor(Math.random() * (lastIndex - index + 1))
|
||||
const value = result[rand]
|
||||
result[rand] = result[index]
|
||||
result[index] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export default sampleSize
|
||||
|
||||
Reference in New Issue
Block a user