MCPcopy Create free account
hub / github.com/jashkenas/underscore / sample

Function sample

underscore.js:1568–1584  ·  view source on GitHub ↗
(obj, n, guard)

Source from the content-addressed store, hash-verified

1566 // If **n** is not specified, returns a single random element.
1567 // The internal `guard` argument allows it to work with `_.map`.
1568 function sample(obj, n, guard) {
1569 if (n == null || guard) {
1570 if (!isArrayLike(obj)) obj = values(obj);
1571 return obj[random(obj.length - 1)];
1572 }
1573 var sample = toArray(obj);
1574 var length = getLength(sample);
1575 n = Math.max(Math.min(n, length), 0);
1576 var last = length - 1;
1577 for (var index = 0; index < n; index++) {
1578 var rand = random(index, last);
1579 var temp = sample[index];
1580 sample[index] = sample[rand];
1581 sample[rand] = temp;
1582 }
1583 return sample.slice(0, n);
1584 }
1585
1586 // Shuffle a collection.
1587 function shuffle(obj) {

Callers 1

shuffleFunction · 0.70

Calls 3

valuesFunction · 0.70
randomFunction · 0.70
toArrayFunction · 0.70

Tested by

no test coverage detected