sample.js 1.4 KB

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