sample.js 1005 B

123456789101112131415161718192021222324252627
  1. import isArrayLike from './_isArrayLike.js';
  2. import clone from './clone.js';
  3. import values from './values.js';
  4. import getLength from './_getLength.js';
  5. import random from './random.js';
  6. // Sample **n** random values from a collection using the modern version of the
  7. // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  8. // If **n** is not specified, returns a single random element.
  9. // The internal `guard` argument allows it to work with `_.map`.
  10. export default function sample(obj, n, guard) {
  11. if (n == null || guard) {
  12. if (!isArrayLike(obj)) obj = values(obj);
  13. return obj[random(obj.length - 1)];
  14. }
  15. var sample = isArrayLike(obj) ? clone(obj) : values(obj);
  16. var length = getLength(sample);
  17. n = Math.max(Math.min(n, length), 0);
  18. var last = length - 1;
  19. for (var index = 0; index < n; index++) {
  20. var rand = random(index, last);
  21. var temp = sample[index];
  22. sample[index] = sample[rand];
  23. sample[rand] = temp;
  24. }
  25. return sample.slice(0, n);
  26. }