1 | // http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array
|
2 | var featureCollection = require('turf-helpers').featureCollection;
|
3 |
|
4 | /**
|
5 | * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random.
|
6 | *
|
7 | * @name sample
|
8 | * @param {FeatureCollection} features set of input features
|
9 | * @param {number} n number of features to select
|
10 | * @return {FeatureCollection} a FeatureCollection with `n` features
|
11 | * @example
|
12 | * var points = turf.random('points', 1000);
|
13 | *
|
14 | * //=points
|
15 | *
|
16 | * var sample = turf.sample(points, 10);
|
17 | *
|
18 | * //=sample
|
19 | */
|
20 | module.exports = function (fc, num) {
|
21 | var outFC = featureCollection(getRandomSubarray(fc.features, num));
|
22 | return outFC;
|
23 | };
|
24 |
|
25 | function getRandomSubarray(arr, size) {
|
26 | var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index;
|
27 | while (i-- > min) {
|
28 | index = Math.floor((i + 1) * Math.random());
|
29 | temp = shuffled[index];
|
30 | shuffled[index] = shuffled[i];
|
31 | shuffled[i] = temp;
|
32 | }
|
33 | return shuffled.slice(min);
|
34 | }
|