f090db107db89bd8587964686cd787f3e5ed35bb
[platform/framework/web/crosswalk-tizen.git] /
1 var baseRandom = require('../internal/baseRandom'),
2     isIterateeCall = require('../internal/isIterateeCall'),
3     shuffle = require('./shuffle'),
4     toIterable = require('../internal/toIterable');
5
6 /* Native method references for those with the same name as other `lodash` methods. */
7 var nativeMin = Math.min;
8
9 /**
10  * Gets a random element or `n` random elements from a collection.
11  *
12  * @static
13  * @memberOf _
14  * @category Collection
15  * @param {Array|Object|string} collection The collection to sample.
16  * @param {number} [n] The number of elements to sample.
17  * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18  * @returns {*} Returns the random sample(s).
19  * @example
20  *
21  * _.sample([1, 2, 3, 4]);
22  * // => 2
23  *
24  * _.sample([1, 2, 3, 4], 2);
25  * // => [3, 1]
26  */
27 function sample(collection, n, guard) {
28   if (guard ? isIterateeCall(collection, n, guard) : n == null) {
29     collection = toIterable(collection);
30     var length = collection.length;
31     return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
32   }
33   var result = shuffle(collection);
34   result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length);
35   return result;
36 }
37
38 module.exports = sample;