Skip to content

Commit

Permalink
added support for weird nested feature collections
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielJDufour committed Jun 22, 2023
1 parent a8c20c5 commit b9b43e6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
29 changes: 21 additions & 8 deletions mpoly.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@ const getDepth = require("get-depth");
const meta = require("@turf/meta");
const booleanClockwise = require("@turf/boolean-clockwise").default;

// supports nested feature collections
function eachPart(it, callback) {
if (Array.isArray(it.features)) {
it.features.forEach(feat => {
eachPart(feat, callback);
});
} else {
callback(it);
}
}

function each(geom, callback) {
// pre-processing steps
if (typeof geom === "string") geom = JSON.parse(geom);
Expand All @@ -25,14 +36,16 @@ function each(geom, callback) {
});
callback(current);
} else if ("type" in geom) {
meta.geomEach(geom, it => {
if (it.type === "Polygon") {
callback(it.coordinates);
} else if (it.type === "MultiPolygon") {
it.coordinates.forEach(polygon => {
callback(polygon);
});
}
eachPart(geom, part => {
meta.geomEach(part, it => {
if (it.type === "Polygon") {
callback(it.coordinates);
} else if (it.type === "MultiPolygon") {
it.coordinates.forEach(polygon => {
callback(polygon);
});
}
});
});
} else if (Array.isArray(geom)) {
const depth = getDepth(geom);
Expand Down
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,17 @@ test("mpoly.get (geojson)", ({ eq }) => {
]
]);
});

test("nested feature collection", ({ eq }) => {
const polys = mpoly.get({
type: "FeatureCollection",
features: [
{
type: "FeatureCollection",
features: [MultiPolygon]
},
Polygon
]
});
eq(polys.length, 3);
});

0 comments on commit b9b43e6

Please sign in to comment.