mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-10 10:57:49 +00:00
Changed to function as documented. (#3596)
This commit is contained in:
committed by
John-David Dalton
parent
75690245aa
commit
77c128fc20
@@ -1,4 +1,5 @@
|
|||||||
import copyArray from './.internal/copyArray.js'
|
import copyArray from './.internal/copyArray.js'
|
||||||
|
import slice from './slice.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets `n` random elements at unique keys from `array` up to the
|
* Gets `n` random elements at unique keys from `array` up to the
|
||||||
@@ -18,13 +19,14 @@ import copyArray from './.internal/copyArray.js'
|
|||||||
* // => [2, 3, 1]
|
* // => [2, 3, 1]
|
||||||
*/
|
*/
|
||||||
function sampleSize(array, n) {
|
function sampleSize(array, n) {
|
||||||
|
n = n == null ? 1 : n
|
||||||
const length = array == null ? 0 : array.length
|
const length = array == null ? 0 : array.length
|
||||||
if (!length || n < 1) {
|
if (!length || n < 1) {
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
n = n > length ? length : n
|
n = n > length ? length : n
|
||||||
let index = -1
|
let index = -1
|
||||||
const lastIndex = n - 1
|
const lastIndex = length - 1
|
||||||
const result = copyArray(array)
|
const result = copyArray(array)
|
||||||
while (++index < n) {
|
while (++index < n) {
|
||||||
const rand = index + Math.floor(Math.random() * (lastIndex - index + 1))
|
const rand = index + Math.floor(Math.random() * (lastIndex - index + 1))
|
||||||
@@ -32,7 +34,7 @@ function sampleSize(array, n) {
|
|||||||
result[rand] = result[index]
|
result[rand] = result[index]
|
||||||
result[index] = value
|
result[index] = value
|
||||||
}
|
}
|
||||||
return result
|
return slice(result, 0, n);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default sampleSize
|
export default sampleSize
|
||||||
|
|||||||
Reference in New Issue
Block a user