import { feature } from 'topojson-client' import type { BahiaFeature } from '@/lib/bahiaGeometriesTypes' import type { GeometryCollection, Topology } from 'topojson-specification' type GeometryModuleBase, TObjectName extends string> = { topology: Topology<{ [key in TObjectName]: GeometryCollection }> features: readonly BahiaFeature[] } type IndexedGeometryModule< Properties extends Record, TObjectName extends string, KeyProperty extends keyof Properties & string, > = GeometryModuleBase & { getFeatureByKey: (key: Properties[KeyProperty]) => BahiaFeature | undefined } type BuildGeometryModuleOptions< Properties extends Record, TObjectName extends string, KeyProperty extends keyof Properties & string, > = { topology: Topology<{ [key in TObjectName]: GeometryCollection }> objectName: TObjectName keyProperty?: KeyProperty } export function buildGeometryModuleFromTopology< Properties extends Record, TObjectName extends string, KeyProperty extends keyof Properties & string, >( options: BuildGeometryModuleOptions & { keyProperty: KeyProperty }, ): IndexedGeometryModule export function buildGeometryModuleFromTopology< Properties extends Record, TObjectName extends string, >( options: BuildGeometryModuleOptions, ): GeometryModuleBase export function buildGeometryModuleFromTopology< Properties extends Record, TObjectName extends string, KeyProperty extends keyof Properties & string, >({ topology, objectName, keyProperty, }: BuildGeometryModuleOptions): | GeometryModuleBase | IndexedGeometryModule { const features = feature(topology, topology.objects[objectName]) .features as BahiaFeature[] const base: GeometryModuleBase = { topology, features, } if (!keyProperty) { return base } const featuresByKey = new Map(features.map((entry) => [entry.properties[keyProperty], entry])) return { ...base, getFeatureByKey: (key) => featuresByKey.get(key), } }