Merge pull request #281 from ryantenney/master

Array Shuffle
This commit is contained in:
Jeremy Ashkenas
2011-10-04 14:11:30 -07:00
3 changed files with 34 additions and 1 deletions

View File

@@ -141,7 +141,8 @@
<a href="#any">any</a>, <a href="#include">include</a>,
<a href="#invoke">invoke</a>, <a href="#pluck">pluck</a>,
<a href="#max">max</a>, <a href="#min">min</a>,
<a href="#sortBy">sortBy</a>, <a href="#groupBy">groupBy</a>, <a href="#sortedIndex">sortedIndex</a>,
<a href="#sortBy">sortBy</a>, <a href="#groupBy">groupBy</a>,
<a href="#sortedIndex">sortedIndex</a>, <a href="#shuffle">shuffle</a>,
<a href="#toArray">toArray</a>, <a href="#size">size</a></span>
</p>
@@ -462,6 +463,16 @@ _.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
<pre>
_.sortedIndex([10, 20, 30, 40, 50], 35);
=&gt; 3
</pre>
<p id="shuffle">
<b class="header">shuffle</b><code>_.shuffle(list)</code>
<br />
Returns a shuffled copy of <b>list</b>.
</p>
<pre>
_.shuffle([1, 2, 3, 4, 5, 6]);
=&gt; [4, 1, 6, 3, 5, 2]
</pre>
<p id="toArray">

View File

@@ -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');

View File

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