From f4cba513b96a12367cbf6f5e704b6bfbcfdb492e Mon Sep 17 00:00:00 2001 From: Ryan W Tenney Date: Thu, 25 Aug 2011 21:44:29 +0000 Subject: [PATCH] Added function shuffle, with test case. --- index.html | 23 ++++++++++++++++++++++- test/collections.js | 7 +++++++ underscore.js | 15 +++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index f04572ff9..3254edcfc 100644 --- a/index.html +++ b/index.html @@ -65,6 +65,7 @@ margin: 0px 0 30px; } + @@ -141,7 +142,8 @@ any, include, invoke, pluck, max, min, - sortBy, groupBy, sortedIndex, + sortBy, groupBy, + sortedIndex, shuffle, toArray, size

@@ -464,6 +466,25 @@ _.sortedIndex([10, 20, 30, 40, 50], 35); => 3 +

+ 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) {