Skip to content

Commit

Permalink
lodash: Move shuffle to the "Arrays" category and optimize. [jddalton]
Browse files Browse the repository at this point in the history
  • Loading branch information
jdalton committed May 1, 2012
1 parent be713e0 commit e307f9f
Showing 1 changed file with 28 additions and 26 deletions.
54 changes: 28 additions & 26 deletions lodash.js
Expand Up @@ -706,32 +706,6 @@
'inLoop': '!' + filterFactoryOptions.inLoop
});

/**
* Produces a new array of shuffled `collection` values, using a version of the
* Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns a new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(collection) {
var rand,
result = [];

forEach(collection, function(value, index) {
rand = Math.floor(Math.random() * (index + 1));
result[index] = result[rand];
result[rand] = value;
});
return result;
}

/**
* Gets the number of values in the `collection`.
*
Expand Down Expand Up @@ -1265,6 +1239,34 @@
return slice.call(array, (n == undefined || guard) ? 1 : n);
}

/**
* Produces a new array of shuffled `array` values, using a version of the
* Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to shuffle.
* @returns {Array} Returns a new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(array) {
var rand,
index = -1,
length = array.length,
result = Array(length);

while (++index < length) {
rand = Math.floor(Math.random() * (index + 1));
result[index] = result[rand];
result[rand] = array[index];
}
return result;
}

/**
* Computes the union of the passed-in arrays.
*
Expand Down

0 comments on commit e307f9f

Please sign in to comment.