mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-11 11:27:50 +00:00
Fix _.shuffle on small collections. [closes #609]
This commit is contained in:
15
lodash.js
15
lodash.js
@@ -5242,19 +5242,16 @@
|
|||||||
function shuffle(collection) {
|
function shuffle(collection) {
|
||||||
collection = toIterable(collection);
|
collection = toIterable(collection);
|
||||||
|
|
||||||
var index = 0,
|
var index = -1,
|
||||||
length = collection.length,
|
length = collection.length,
|
||||||
result = Array(length);
|
result = Array(length);
|
||||||
|
|
||||||
if (length) {
|
|
||||||
result[index] = collection[index];
|
|
||||||
}
|
|
||||||
while (++index < length) {
|
while (++index < length) {
|
||||||
var value = collection[index],
|
var rand = baseRandom(0, index);
|
||||||
rand = baseRandom(0, index - 1);
|
if (index != rand) {
|
||||||
|
result[index] = result[rand];
|
||||||
result[index] = result[rand];
|
}
|
||||||
result[rand] = value;
|
result[rand] = collection[index];
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8907,9 +8907,12 @@
|
|||||||
deepEqual(_.shuffle(object).sort(), array);
|
deepEqual(_.shuffle(object).sort(), array);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should shuffle an object', 1, function() {
|
test('should shuffle small collections', 1, function() {
|
||||||
var actual = _.shuffle(object);
|
var actual = _.times(1000, function() {
|
||||||
deepEqual(actual.sort(), array);
|
return _.shuffle([1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
deepEqual(_.sortBy(_.uniq(actual, String), '0'), [[1, 2], [2, 1]]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should treat number values for `collection` as empty', 1, function() {
|
test('should treat number values for `collection` as empty', 1, function() {
|
||||||
|
|||||||
Reference in New Issue
Block a user