Permalink
Browse files

Fixes #689 -- allow _.random() to be called with just a max, and use …

…it in _.shuffle
  • Loading branch information...
1 parent 7f8161e commit b18f4da28d776d5e48a8f77e2989c60ac39bf8d8 @jashkenas committed Sep 18, 2012
Showing with 5 additions and 1 deletion.
  1. +5 −1 underscore.js
View
@@ -276,7 +276,7 @@
var index = 0;
var shuffled = [];
each(obj, function(value) {
- rand = Math.floor(Math.random() * ++index);
+ rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
@fmdkdd

fmdkdd Nov 6, 2012

Since we use the postfix increment, index++ is the same value as index - 1 in each iteration. The following is equivalent, but simpler:

rand = _.random(index);
shuffled[index++] = shuffled[rand];
shuffled[rand] = value;
});
@@ -971,6 +971,10 @@
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
+ if (max == null) {
+ max = min;
+ min = 0;
+ }
return min + (0 | Math.random() * (max - min + 1));
};

0 comments on commit b18f4da

Please sign in to comment.