index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. var helpers = require('@turf/helpers');
  3. // http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array
  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} featurecollection set of input features
  9. * @param {number} num number of features to select
  10. * @returns {FeatureCollection} a FeatureCollection with `n` features
  11. * @example
  12. * var points = turf.randomPoint(100, {bbox: [-80, 30, -60, 60]});
  13. *
  14. * var sample = turf.sample(points, 5);
  15. *
  16. * //addToMap
  17. * var addToMap = [points, sample]
  18. * turf.featureEach(sample, function (currentFeature) {
  19. * currentFeature.properties['marker-size'] = 'large';
  20. * currentFeature.properties['marker-color'] = '#000';
  21. * });
  22. */
  23. function sample(featurecollection, num) {
  24. if (!featurecollection) throw new Error("featurecollection is required");
  25. if (num === null || num === undefined) throw new Error("num is required");
  26. if (typeof num !== "number") throw new Error("num must be a number");
  27. var outFC = helpers.featureCollection(
  28. getRandomSubarray(featurecollection.features, num)
  29. );
  30. return outFC;
  31. }
  32. function getRandomSubarray(arr, size) {
  33. var shuffled = arr.slice(0),
  34. i = arr.length,
  35. min = i - size,
  36. temp,
  37. index;
  38. while (i-- > min) {
  39. index = Math.floor((i + 1) * Math.random());
  40. temp = shuffled[index];
  41. shuffled[index] = shuffled[i];
  42. shuffled[i] = temp;
  43. }
  44. return shuffled.slice(min);
  45. }
  46. module.exports = sample;
  47. module.exports.default = sample;