From f4cba513b96a12367cbf6f5e704b6bfbcfdb492e Mon Sep 17 00:00:00 2001
From: Ryan W Tenney
+ shuffle_.shuffle(list)
+
+ Returns a shuffled list.
+
+_.shuffle([1, 2, 3, 4, 5, 6]); +=> +(reshuffle) ++ +
toArray_.toArray(list)
diff --git a/test/collections.js b/test/collections.js
index 005ee169e..9afe95849 100644
--- a/test/collections.js
+++ b/test/collections.js
@@ -204,6 +204,13 @@ $(document).ready(function() {
equals(index, 3, '35 should be inserted at index 3');
});
+ test('collections: shuffle', function() {
+ var numbers = _.range(10);
+ var shuffled = _.shuffle(numbers).sort();
+ notStrictEqual(numbers, shuffled, 'original object is unmodified');
+ equals(shuffled.join(','), numbers.join(','), 'contains the same members before and after shuffle');
+ });
+
test('collections: toArray', function() {
ok(!_.isArray(arguments), 'arguments object is not an array');
ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array');
diff --git a/underscore.js b/underscore.js
index 0d587b41c..a19f3186e 100644
--- a/underscore.js
+++ b/underscore.js
@@ -239,6 +239,21 @@
return result.value;
};
+ // Shuffle an array.
+ _.shuffle = function(obj) {
+ var shuffled = [], rand;
+ each(obj, function(value, index, list) {
+ if (index == 0) {
+ shuffled[0] = value;
+ } else {
+ rand = Math.floor(Math.random() * (index + 1));
+ shuffled[index] = shuffled[rand];
+ shuffled[rand] = value;
+ }
+ });
+ return shuffled;
+ };
+
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {