Optimize _.sample.

This commit is contained in:
John-David Dalton
2013-09-08 01:14:42 -05:00
parent 692521c49d
commit 1460e46d1f

View File

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