index.js 1.5 KB

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