mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-09 18:37:50 +00:00
lodash: Move shuffle to the "Arrays" category and optimize. [jddalton]
Former-commit-id: 6f08cc15a5a1b0197e080d5fc21309b84cabaf6a
This commit is contained in:
54
lodash.js
54
lodash.js
@@ -706,32 +706,6 @@
|
|||||||
'inLoop': '!' + filterFactoryOptions.inLoop
|
'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`.
|
* Gets the number of values in the `collection`.
|
||||||
*
|
*
|
||||||
@@ -1265,6 +1239,34 @@
|
|||||||
return slice.call(array, (n == undefined || guard) ? 1 : n);
|
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.
|
* Computes the union of the passed-in arrays.
|
||||||
*
|
*
|
||||||
|
|||||||
Reference in New Issue
Block a user