sample.js 1011 B

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