-
Notifications
You must be signed in to change notification settings - Fork 224
/
sample.js
28 lines (25 loc) · 993 Bytes
/
sample.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import shuffle from "./shuffle";
/**
* Create a [simple random sample](http://en.wikipedia.org/wiki/Simple_random_sample)
* from a given array of `n` elements.
*
* The sampled values will be in any order, not necessarily the order
* they appear in the input.
*
* @param {Array<any>} x input array. can contain any type
* @param {number} n count of how many elements to take
* @param {Function} [randomSource=Math.random] an optional entropy source that
* returns numbers between 0 inclusive and 1 exclusive: the range [0, 1)
* @return {Array} subset of n elements in original array
*
* @example
* var values = [1, 2, 4, 5, 6, 7, 8, 9];
* sample(values, 3); // returns 3 random values, like [2, 5, 8];
*/
function sample(x, n, randomSource) {
// shuffle the original array using a fisher-yates shuffle
const shuffled = shuffle(x, randomSource);
// and then return a subset of it - the first `n` elements.
return shuffled.slice(0, n);
}
export default sample;