UNPKG

620 BJavaScriptView Raw
1import baseRandom from './_baseRandom';
2import isArrayLike from './isArrayLike';
3import values from './values';
4
5/**
6 * Gets a random element from `collection`.
7 *
8 * @static
9 * @memberOf _
10 * @since 2.0.0
11 * @category Collection
12 * @param {Array|Object} collection The collection to sample.
13 * @returns {*} Returns the random element.
14 * @example
15 *
16 * _.sample([1, 2, 3, 4]);
17 * // => 2
18 */
19function sample(collection) {
20 var array = isArrayLike(collection) ? collection : values(collection),
21 length = array.length;
22
23 return length > 0 ? array[baseRandom(0, length - 1)] : undefined;
24}
25
26export default sample;