import { countryType, populateCitiesType, returnT, StateFnType } from "../types" import { PATH, populateCities, PATH_LITE } from "../utils" export const State: StateFnType = stateHandler() export const StateLite: StateFnType = stateHandler('lite') function stateHandler(type?: 'lite'): StateFnType { const path = type === 'lite' ? PATH_LITE : PATH const fn: StateFnType = function (countryIso2: countryType, stateIso?: populateCitiesType | string, populate?: populateCitiesType): returnT { if (!countryIso2) { throw new TypeError("Country iso2 type missing") } try { const stateRecords: Array<{ iso?: string }> = require(`${path}/states/${countryIso2}/index.json`) if (!stateIso || typeof stateIso === 'object') { const states: Array<{}> = [] for (const { ...state } of stateRecords) { populateCities(countryIso2, state, typeof stateIso === 'object' ? stateIso.cities : false, type) states.push(state) } return states } const state: any = stateRecords.find(({ iso }) => iso === stateIso) populate?.cities && populateCities(countryIso2, state, true, type) return state ?? null } catch (e) { return null } } return fn }