Added function shuffle, with test case.

This commit is contained in:
Ryan W Tenney
2011-08-25 21:44:29 +00:00
parent 610b347174
commit f4cba513b9
3 changed files with 44 additions and 1 deletions

View File

@@ -65,6 +65,7 @@
margin: 0px 0 30px;
}
</style>
<script type="text/javascript" src="underscore-min.js"></script>
</head>
<body>
@@ -141,7 +142,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>
@@ -464,6 +466,25 @@ _.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 <b>list</b>.
</p>
<pre>
_.shuffle([1, 2, 3, 4, 5, 6]);
=&gt; <span id="shuffled"></span>
<small><i><b><a href="javascript:doShuffle();">(reshuffle)</a></b></i></small>
</pre>
<script type="text/javascript">
function doShuffle() {
var el = document.getElementById("shuffled");
while (el.firstChild && el.removeChild(el.firstChild));
el.appendChild(document.createTextNode("[" + _.shuffle([1, 2, 3, 4, 5, 6]).join(', ') + "]"));
}
doShuffle();
</script>
<p id="toArray">
<b class="header">toArray</b><code>_.toArray(list)</code>
<br />

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