mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-11 19:37:49 +00:00
Optimize _.sample.
This commit is contained in:
@@ -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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user