UNPKG

@ideal-postcodes/jsutil

Version:

Browser Address Autocomplete for api.ideal-postcodes.co.uk

70 lines (69 loc) 2.09 kB
import { isGbrAddress } from "./types"; import { isSelect, isInput, hasValue, change, optionsHasText } from "./input"; const UK = "United Kingdom"; const IOM = "Isle of Man"; const EN = "England"; const SC = "Scotland"; const WA = "Wales"; const NI = "Northern Ireland"; const CI = "Channel Islands"; export const toCountry = (address) => { const country = address.country; if (country === EN) return UK; if (country === SC) return UK; if (country === WA) return UK; if (country === NI) return UK; if (country === IOM) return IOM; if (isGbrAddress(address)) { if (country === CI) { if (/^GY/.test(address.postcode)) return "Guernsey"; if (/^JE/.test(address.postcode)) return "Jersey"; } } return country; }; export const updateCountry = (select, address) => { if (!select) return; if (isSelect(select)) { const bcc = toCountry(address); if (hasValue(select, bcc)) { change({ e: select, value: bcc }); return; } if (hasValue(select, address.country_iso_2)) { change({ e: select, value: address.country_iso_2 }); return; } if (hasValue(select, address.country_iso)) { change({ e: select, value: address.country_iso }); return; } let text = optionsHasText(select, bcc); if (text.length > 0) { change({ e: select, value: text[0].value || "" }); return; } text = optionsHasText(select, address.country_iso_2); if (text.length > 0) { change({ e: select, value: text[0].value || "" }); return; } text = optionsHasText(select, address.country_iso); if (text.length > 0) { change({ e: select, value: text[0].value || "" }); return; } } if (isInput(select)) { const bcc = toCountry(address); change({ e: select, value: bcc }); } };