Skip to content

Commit

Permalink
Tighten up _.sample implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentwoo committed Aug 11, 2013
1 parent 06f24c6 commit 673aed4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
2 changes: 2 additions & 0 deletions test/collections.js
Expand Up @@ -426,6 +426,8 @@ $(document).ready(function() {
ok(_.contains(numbers, _.sample(numbers)), 'sampling a single element returns something from the array');
strictEqual(_.sample([]), null, 'sampling empty array with no number returns null');
notStrictEqual(_.sample([], 5), [], 'sampling empty array with a number returns an empty array');
notStrictEqual(_.sample([1, 2, 3], 0), [], 'sampling an array with 0 picks returns an empty array');
throws(function() { _.sample([], -1); }, 'cannot sample a negative number of picks');
});

test('toArray', function() {
Expand Down
14 changes: 6 additions & 8 deletions underscore.js
Expand Up @@ -287,15 +287,13 @@
// If number is not specified, returns only a single sampled object
// Otherwise, returns an array of (min of number and length of array) sampled objects
_.sample = function(obj, number) {
if (!number) {
return obj.length > 0 ? obj[_.random(obj.length - 1)] : null;
} else {
var sampled_indices = _.shuffle(_.range(obj.length));
var sampled_values = [];
for (; number > 0 && sampled_indices.length > 0; --number) {
sampled_values.push(obj[sampled_indices.pop()]);
if (typeof number === 'number') {
if (number < 0) {
throw new Error('sample cannot be called with a negative number of picks');
}
return sampled_values;
return _.shuffle(obj).slice(0, number);
} else {
return obj.length > 0 ? obj[_.random(obj.length - 1)] : null;
}
};

Expand Down

0 comments on commit 673aed4

Please sign in to comment.