From b24b8315d376ecea3f917975c8944991ca70bccf Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Tue, 8 Jul 2014 08:28:50 -0700 Subject: [PATCH] Fix `_.shuffle` on small collections. [closes #609] --- lodash.js | 15 ++++++--------- test/test.js | 9 ++++++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lodash.js b/lodash.js index b481db01f..caab4d048 100644 --- a/lodash.js +++ b/lodash.js @@ -5242,19 +5242,16 @@ function shuffle(collection) { collection = toIterable(collection); - var index = 0, + var index = -1, length = collection.length, result = Array(length); - if (length) { - result[index] = collection[index]; - } while (++index < length) { - var value = collection[index], - rand = baseRandom(0, index - 1); - - result[index] = result[rand]; - result[rand] = value; + var rand = baseRandom(0, index); + if (index != rand) { + result[index] = result[rand]; + } + result[rand] = collection[index]; } return result; } diff --git a/test/test.js b/test/test.js index edef0e777..66932555a 100644 --- a/test/test.js +++ b/test/test.js @@ -8907,9 +8907,12 @@ deepEqual(_.shuffle(object).sort(), array); }); - test('should shuffle an object', 1, function() { - var actual = _.shuffle(object); - deepEqual(actual.sort(), array); + test('should shuffle small collections', 1, function() { + var actual = _.times(1000, function() { + 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() {