turf-dissolve.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import clone from "@turf/clone";
  2. import { isObject } from "@turf/helpers";
  3. import { getType } from "@turf/invariant";
  4. import { flattenEach } from "@turf/meta";
  5. import lineDissolve from "./turf-line-dissolve.js";
  6. import polygonDissolve from "./turf-polygon-dissolve.js";
  7. /**
  8. * Transform function: attempts to dissolve geojson objects where possible
  9. * [GeoJSON] -> GeoJSON geometry
  10. *
  11. * @private
  12. * @param {FeatureCollection<LineString|MultiLineString|Polygon|MultiPolygon>} geojson Features to dissolved
  13. * @param {Object} [options={}] Optional parameters
  14. * @param {boolean} [options.mutate=false] Prevent input mutation
  15. * @returns {Feature<MultiLineString|MultiPolygon>} Dissolved Features
  16. */
  17. function dissolve(geojson, options) {
  18. if (options === void 0) { options = {}; }
  19. // Optional parameters
  20. options = options || {};
  21. if (!isObject(options)) {
  22. throw new Error("options is invalid");
  23. }
  24. var mutate = options.mutate;
  25. // Validation
  26. if (getType(geojson) !== "FeatureCollection") {
  27. throw new Error("geojson must be a FeatureCollection");
  28. }
  29. if (!geojson.features.length) {
  30. throw new Error("geojson is empty");
  31. }
  32. // Clone geojson to avoid side effects
  33. // Topojson modifies in place, so we need to deep clone first
  34. if (mutate === false || mutate === undefined) {
  35. geojson = clone(geojson);
  36. }
  37. // Assert homogenity
  38. var type = getHomogenousType(geojson);
  39. if (!type) {
  40. throw new Error("geojson must be homogenous");
  41. }
  42. // Data => Typescript hack
  43. var data = geojson;
  44. switch (type) {
  45. case "LineString":
  46. return lineDissolve(data, options);
  47. case "Polygon":
  48. return polygonDissolve(data, options);
  49. default:
  50. throw new Error(type + " is not supported");
  51. }
  52. }
  53. /**
  54. * Checks if GeoJSON is Homogenous
  55. *
  56. * @private
  57. * @param {GeoJSON} geojson GeoJSON
  58. * @returns {string|null} Homogenous type or null if multiple types
  59. */
  60. function getHomogenousType(geojson) {
  61. var types = {};
  62. flattenEach(geojson, function (feature) {
  63. types[feature.geometry.type] = true;
  64. });
  65. var keys = Object.keys(types);
  66. if (keys.length === 1) {
  67. return keys[0];
  68. }
  69. return null;
  70. }
  71. export default dissolve;