|
Last change
on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 11 days ago |
|
Fix frontend appearance
|
-
Property mode
set to
100644
|
|
File size:
983 bytes
|
| Line | |
|---|
| 1 | define(['./_isArrayLike', './values', './_getLength', './random', './toArray'], function (_isArrayLike, values, _getLength, random, toArray) {
|
|---|
| 2 |
|
|---|
| 3 | // Sample **n** random values from a collection using the modern version of the
|
|---|
| 4 | // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
|
|---|
| 5 | // If **n** is not specified, returns a single random element.
|
|---|
| 6 | // The internal `guard` argument allows it to work with `_.map`.
|
|---|
| 7 | function sample(obj, n, guard) {
|
|---|
| 8 | if (n == null || guard) {
|
|---|
| 9 | if (!_isArrayLike(obj)) obj = values(obj);
|
|---|
| 10 | return obj[random(obj.length - 1)];
|
|---|
| 11 | }
|
|---|
| 12 | var sample = toArray(obj);
|
|---|
| 13 | var length = _getLength(sample);
|
|---|
| 14 | n = Math.max(Math.min(n, length), 0);
|
|---|
| 15 | var last = length - 1;
|
|---|
| 16 | for (var index = 0; index < n; index++) {
|
|---|
| 17 | var rand = random(index, last);
|
|---|
| 18 | var temp = sample[index];
|
|---|
| 19 | sample[index] = sample[rand];
|
|---|
| 20 | sample[rand] = temp;
|
|---|
| 21 | }
|
|---|
| 22 | return sample.slice(0, n);
|
|---|
| 23 | }
|
|---|
| 24 |
|
|---|
| 25 | return sample;
|
|---|
| 26 |
|
|---|
| 27 | });
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.