Simplify shuffle and sample.

This commit is contained in:
John-David Dalton
2017-02-06 23:53:17 -08:00
parent b0980a90fc
commit cb7612aef6
11 changed files with 44 additions and 162 deletions

View File

@@ -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