diff --git a/packages/turf-helpers/index.ts b/packages/turf-helpers/index.ts index d6cd0d7dc..849dd457c 100644 --- a/packages/turf-helpers/index.ts +++ b/packages/turf-helpers/index.ts @@ -18,6 +18,23 @@ import { import { Id } from "./lib/geojson.js"; export * from "./lib/geojson.js"; +// I'd normally put this in @turf/meta but it isn't full-TypeScript yet +export function* iterFeatures< + G extends GeometryObject, + P extends GeoJsonProperties, +>( + geojson: Feature | FeatureCollection +): Generator<{ feature: Feature; featureIndex: number }, void, unknown> { + if (geojson.type === "Feature") { + yield { feature: geojson, featureIndex: 0 }; + } else { + const features = geojson.features; + for (let i = 0; i < features.length; i++) { + yield { feature: features[i], featureIndex: i }; + } + } +} + /** * @module helpers */ diff --git a/packages/turf-moran-index/index.ts b/packages/turf-moran-index/index.ts index 83a5e9e5b..4ea214448 100644 --- a/packages/turf-moran-index/index.ts +++ b/packages/turf-moran-index/index.ts @@ -1,6 +1,6 @@ import { FeatureCollection } from "geojson"; import { distanceWeight as spatialWeight } from "@turf/distance-weight"; -import { featureEach } from "@turf/meta"; +import { iterFeatures } from "@turf/helpers"; /** * @typedef {object} MoranIndex @@ -86,11 +86,11 @@ function moranIndex( }); const y: number[] = []; - featureEach(fc, (feature) => { + for (const { feature } of iterFeatures(fc)) { const feaProperties = feature.properties || {}; // validate inputField exists y.push(feaProperties[inputField]); - }); + } const yMean = mean(y); const yVar = variance(y); diff --git a/packages/turf-nearest-point/index.ts b/packages/turf-nearest-point/index.ts index 2d6882a06..8cf7cae3a 100644 --- a/packages/turf-nearest-point/index.ts +++ b/packages/turf-nearest-point/index.ts @@ -1,8 +1,7 @@ import { Feature, FeatureCollection, GeoJsonProperties, Point } from "geojson"; -import { Coord, Units } from "@turf/helpers"; +import { Coord, iterFeatures, Units } from "@turf/helpers"; import { clone } from "@turf/clone"; import { distance } from "@turf/distance"; -import { featureEach } from "@turf/meta"; interface NearestPoint

extends Feature { @@ -51,13 +50,14 @@ function nearestPoint

( let minDist = Infinity; let bestFeatureIndex = 0; - featureEach(points, (pt, featureIndex) => { + for (const { feature: pt, featureIndex } of iterFeatures(points)) { const distanceToPoint = distance(targetPoint, pt, options); if (distanceToPoint < minDist) { bestFeatureIndex = featureIndex; minDist = distanceToPoint; } - }); + } + const nearestPoint = clone(points.features[bestFeatureIndex]); return {