sample.js 1008 B

1234567891011121314151617181920212223242526272829
  1. var _isArrayLike = require('./_isArrayLike.js');
  2. var values = require('./values.js');
  3. var _getLength = require('./_getLength.js');
  4. var random = require('./random.js');
  5. var toArray = require('./toArray.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. 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 = toArray(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. }
  27. module.exports = sample;