You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
1.0 KiB

  1. var arraySampleSize = require('./_arraySampleSize'),
  2. baseSampleSize = require('./_baseSampleSize'),
  3. isArray = require('./isArray'),
  4. isIterateeCall = require('./_isIterateeCall'),
  5. toInteger = require('./toInteger');
  6. /**
  7. * Gets `n` random elements at unique keys from `collection` up to the
  8. * size of `collection`.
  9. *
  10. * @static
  11. * @memberOf _
  12. * @since 4.0.0
  13. * @category Collection
  14. * @param {Array|Object} collection The collection to sample.
  15. * @param {number} [n=1] The number of elements to sample.
  16. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  17. * @returns {Array} Returns the random elements.
  18. * @example
  19. *
  20. * _.sampleSize([1, 2, 3], 2);
  21. * // => [3, 1]
  22. *
  23. * _.sampleSize([1, 2, 3], 4);
  24. * // => [2, 3, 1]
  25. */
  26. function sampleSize(collection, n, guard) {
  27. if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
  28. n = 1;
  29. } else {
  30. n = toInteger(n);
  31. }
  32. var func = isArray(collection) ? arraySampleSize : baseSampleSize;
  33. return func(collection, n);
  34. }
  35. module.exports = sampleSize;