diff --git a/sampleSize.js b/sampleSize.js index aba63eb42..c6ae21b10 100644 --- a/sampleSize.js +++ b/sampleSize.js @@ -1,4 +1,5 @@ import copyArray from './.internal/copyArray.js' +import slice from './slice.js' /** * 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] */ function sampleSize(array, n) { + n = n == null ? 1 : 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 lastIndex = length - 1 const result = copyArray(array) while (++index < n) { const rand = index + Math.floor(Math.random() * (lastIndex - index + 1)) @@ -32,7 +34,7 @@ function sampleSize(array, n) { result[rand] = result[index] result[index] = value } - return result + return slice(result, 0, n); } export default sampleSize