Skip to content

Commit

Permalink
Tweaking _.sample to taste.
Browse files Browse the repository at this point in the history
  • Loading branch information
jashkenas committed Sep 4, 2013
1 parent 8f616a6 commit 8778df3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
2 changes: 1 addition & 1 deletion test/collections.js
Expand Up @@ -467,7 +467,7 @@ $(document).ready(function() {
strictEqual(_.sample([]), undefined, 'sampling empty array with no number returns undefined');
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');
deepEqual(_.sample([1, 2], -1), [], 'sampling a negative number of picks returns an empty array');
});

test('toArray', function() {
Expand Down
23 changes: 10 additions & 13 deletions underscore.js
Expand Up @@ -283,19 +283,6 @@
return result.value;
};

// Sample a number of random values from an array.
// 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 (typeof number === 'number') {
if (number < 0) {
throw new Error('sample cannot be called with a negative number of picks');
}
return _.shuffle(obj).slice(0, number);
}
return obj[_.random(obj.length - 1)];
};

// Shuffle an array.
_.shuffle = function(obj) {
var rand;
Expand All @@ -309,6 +296,16 @@
return shuffled;
};

// Sample **n** random values from an array.
// If **n** is not specified, returns a single random element from the array.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (arguments.length < 2 || guard) {
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};

// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
Expand Down

0 comments on commit 8778df3

Please sign in to comment.