From b9b43e6158cdd86f7df54661c0f9c9f9bb3123b1 Mon Sep 17 00:00:00 2001 From: DanielJDufour Date: Wed, 21 Jun 2023 20:50:46 -0400 Subject: [PATCH] added support for weird nested feature collections --- mpoly.js | 29 +++++++++++++++++++++-------- test.js | 14 ++++++++++++++ 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/mpoly.js b/mpoly.js index f14ef7b..5e4c523 100644 --- a/mpoly.js +++ b/mpoly.js @@ -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); @@ -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); diff --git a/test.js b/test.js index 73c7131..7cf3f04 100644 --- a/test.js +++ b/test.js @@ -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); +});