From 1460e46d1f1081cd7ac49b0f82a022925ee633b8 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Sun, 8 Sep 2013 01:14:42 -0500 Subject: [PATCH] Optimize `_.sample`. --- lodash.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lodash.js b/lodash.js index f3d7ee286..863a572f6 100644 --- a/lodash.js +++ b/lodash.js @@ -3888,11 +3888,14 @@ * // => [3, 1] */ function sample(collection, n, guard) { - if (!isArray(collection)) { - collection = toArray(collection); + var length = collection ? collection.length : 0; + if (typeof length != 'number') { + collection = values(collection); + } else if (support.unindexedChars && isString(collection)) { + collection = collection.split(''); } if (n == null || guard) { - return collection[random(collection.length - 1)]; + return collection[random(length - 1)]; } var result = shuffle(collection); result.length = nativeMin(nativeMax(0, n), result.length);