2281d4f65b23ecef2bd5ac687db49272e02a2001
[platform/framework/web/crosswalk-tizen.git] /
1 var baseRandom = require('../internal/baseRandom'),
2     toIterable = require('../internal/toIterable');
3
4 /**
5  * Creates an array of shuffled values, using a version of the
6  * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
7  *
8  * @static
9  * @memberOf _
10  * @category Collection
11  * @param {Array|Object|string} collection The collection to shuffle.
12  * @returns {Array} Returns the new shuffled array.
13  * @example
14  *
15  * _.shuffle([1, 2, 3, 4]);
16  * // => [4, 1, 3, 2]
17  */
18 function shuffle(collection) {
19   collection = toIterable(collection);
20
21   var index = -1,
22       length = collection.length,
23       result = Array(length);
24
25   while (++index < length) {
26     var rand = baseRandom(0, index);
27     if (index != rand) {
28       result[index] = result[rand];
29     }
30     result[rand] = collection[index];
31   }
32   return result;
33 }
34
35 module.exports = shuffle;