-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
Copy pathshuffle.js
36 lines (32 loc) · 897 Bytes
/
shuffle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import baseRandom from '../internal/baseRandom';
import toIterable from '../internal/toIterable';
/**
* Creates an array of shuffled values, using a version of the Fisher-Yates
* shuffle. See [Wikipedia](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle)
* for more details.
*
* @static
* @memberOf _
* @category Collection
* @param {Array|Object|string} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
collection = toIterable(collection);
var index = -1,
length = collection.length,
result = Array(length);
while (++index < length) {
var rand = baseRandom(0, index);
if (index != rand) {
result[index] = result[rand];
}
result[rand] = collection[index];
}
return result;
}
export default shuffle;