From 4a5f8fa974aa483519fcf8bd30bb921f3b7922b5 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Thu, 1 Sep 2016 20:03:40 -0700 Subject: [PATCH] Split `_.sample` out to `arraySample`. --- lodash.js | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lodash.js b/lodash.js index 063e111a0..bc2674b3d 100644 --- a/lodash.js +++ b/lodash.js @@ -712,6 +712,19 @@ return accumulator; } + /** + * A specialized version of `_.sample` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. @@ -9575,10 +9588,7 @@ * // => 2 */ function sample(collection) { - var array = isArrayLike(collection) ? collection : values(collection), - length = array.length; - - return length > 0 ? array[baseRandom(0, length - 1)] : undefined; + return arraySample(isArrayLike(collection) ? collection : values(collection)); } /**