Optimize _.sample.

This commit is contained in:
jdalton
2015-05-22 22:08:45 -07:00
parent 5f845aa6f8
commit 69f51896c9

View File

@@ -7086,8 +7086,21 @@
var length = collection.length; var length = collection.length;
return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
} }
var result = shuffle(collection); var result = toArray(collection),
result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length); length = result.length,
index = length;
n = nativeMin(n < 0 ? 0 : (+n || 0), length);
var end = length - n;
while (index-- > end) {
var rand = baseRandom(0, index),
othIndex = length - index - 1,
othValue = result[othIndex];
result[othIndex] = result[rand];
result[rand] = othValue;
}
result.length = n;
return result; return result;
} }
@@ -7106,20 +7119,7 @@
* // => [4, 1, 3, 2] * // => [4, 1, 3, 2]
*/ */
function shuffle(collection) { function shuffle(collection) {
collection = toIterable(collection); return sample(collection, Infinity);
var index = -1,
length = collection.length,
result = Array(length);
while (++index < length) {
var rand = baseRandom(0, index);
if (index != rand) {
result[index] = result[rand];
}
result[rand] = collection[index];
}
return result;
} }
/** /**