UNPKG

countries-ts

Version:

A powerful TypeScript library with 60+ functions for country data - search, validate, format, compare, and more. Zero dependencies.

542 lines (541 loc) 23.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getNativeNames = exports.getByNativeName = exports.getDemonyms = exports.getByDemonym = exports.getCountryStatistics = exports.getPopulationDensity = exports.getSmallestCountries = exports.getLargestCountries = exports.getLeastPopulousCountries = exports.getMostPopulousCountries = exports.areBorderingCountries = exports.getBorderingCountries = exports.getDistanceBetweenCountries = exports.getCountriesByCoordinates = exports.getCountriesInTimezone = exports.searchCountriesAdvanced = exports.getIsoCodeMapping = exports.getByIsoCode = exports.getCountryByCapital = exports.getCapitals = exports.getFlagUrl = exports.getRandomCountries = exports.getRandomCountry = exports.sortCountriesBy = exports.getNeighboringCountries = exports.compareCountries = exports.formatPhoneNumber = exports.formatCountryName = exports.isValidPhoneCode = exports.isValidCurrencyCode = exports.isValidCountryCode = exports.getCountriesByLanguages = exports.getLanguages = exports.getCountriesUsingCurrency = exports.getCurrencies = exports.getRegionStats = exports.getCountriesByRegions = exports.getRegions = exports.getByCurrencySymbol = exports.getByMultipleCodes = exports.searchCountries = exports.listCountries = exports.getByCountryCode = exports.getByLanguage = exports.getByCurrency = exports.getByCountry = exports.getByAlpha3 = exports.getByAlpha2 = exports.getByCode = exports.getByCodeArea = void 0; exports.getLanguageDetails = exports.getCurrencyDetails = exports.getRegionsWithNames = exports.getRegionName = exports.validateCountryCodes = exports.getCountriesBatch = exports.exportCountriesToJSON = exports.exportCountriesToCSV = exports.getCountriesBySubregion = exports.getSubregions = void 0; const countries_1 = require("./countries"); const alpha3_codes_1 = require("./alpha3-codes"); const getByCodeArea = (region) => { const result = countries_1.countries.filter((country) => country.region === region); return result; }; exports.getByCodeArea = getByCodeArea; const getByCode = (code) => { return countries_1.countries.find((country) => country.code === code); }; exports.getByCode = getByCode; const getByAlpha2 = (alpha2) => { return countries_1.countries.find((country) => country.code === alpha2.toUpperCase()); }; exports.getByAlpha2 = getByAlpha2; const getByAlpha3 = (alpha3) => { var _a; const alpha3Upper = alpha3.toUpperCase(); const alpha2Code = (_a = Object.entries(alpha3_codes_1.alpha3Codes).find(([_, a3]) => a3 === alpha3Upper)) === null || _a === void 0 ? void 0 : _a[0]; if (!alpha2Code) return undefined; return countries_1.countries.find((country) => country.code === alpha2Code); }; exports.getByAlpha3 = getByAlpha3; const getByCountry = (countryName) => { return countries_1.countries.find((country) => country.label === countryName); }; exports.getByCountry = getByCountry; const getByCurrency = (currencyCode) => { return countries_1.countries.filter((country) => country.currency.code === currencyCode); }; exports.getByCurrency = getByCurrency; const getByLanguage = (languageCode) => { return countries_1.countries.filter((country) => country.language.code === languageCode); }; exports.getByLanguage = getByLanguage; const getByCountryCode = (countryCode) => { const result = countries_1.countries.find((country) => country.countryCode === countryCode); return result; }; exports.getByCountryCode = getByCountryCode; const listCountries = () => { return countries_1.countries; }; exports.listCountries = listCountries; // Fuzzy search functionality const searchCountries = (query, fields) => { const searchFields = fields || ['label', 'capital', 'code']; const normalizedQuery = query.toLowerCase().trim(); return countries_1.countries.filter((country) => { return searchFields.some(field => { const value = country[field]; if (typeof value === 'string') { return value.toLowerCase().includes(normalizedQuery); } if (field === 'currency' && country.currency) { return country.currency.label.toLowerCase().includes(normalizedQuery) || country.currency.code.toLowerCase().includes(normalizedQuery); } if (field === 'language' && country.language) { return country.language.label.toLowerCase().includes(normalizedQuery) || country.language.code.toLowerCase().includes(normalizedQuery); } return false; }); }); }; exports.searchCountries = searchCountries; // Get countries by multiple codes const getByMultipleCodes = (codes) => { return countries_1.countries.filter((country) => codes.includes(country.code)); }; exports.getByMultipleCodes = getByMultipleCodes; // Get countries by currency symbol const getByCurrencySymbol = (symbol) => { return countries_1.countries.filter((country) => country.currency.symbol === symbol); }; exports.getByCurrencySymbol = getByCurrencySymbol; // Region/Continent utilities const getRegions = () => { const regions = new Set(countries_1.countries.map(country => country.region)); return Array.from(regions).sort(); }; exports.getRegions = getRegions; const getCountriesByRegions = (regions) => { return countries_1.countries.filter((country) => regions.includes(country.region)); }; exports.getCountriesByRegions = getCountriesByRegions; const getRegionStats = () => { const stats = countries_1.countries.reduce((acc, country) => { acc[country.region] = (acc[country.region] || 0) + 1; return acc; }, {}); return Object.entries(stats).map(([region, count]) => ({ region, count })); }; exports.getRegionStats = getRegionStats; // Currency utilities const getCurrencies = () => { const currencyMap = new Map(); countries_1.countries.forEach(country => { if (!currencyMap.has(country.currency.code)) { currencyMap.set(country.currency.code, country.currency); } }); return Array.from(currencyMap.values()).sort((a, b) => a.code.localeCompare(b.code)); }; exports.getCurrencies = getCurrencies; const getCountriesUsingCurrency = (currencyCode) => { return countries_1.countries.filter(country => country.currency.code === currencyCode).length; }; exports.getCountriesUsingCurrency = getCountriesUsingCurrency; // Language utilities const getLanguages = () => { const languageMap = new Map(); countries_1.countries.forEach(country => { if (country.language && country.language.code && !languageMap.has(country.language.code)) { languageMap.set(country.language.code, country.language); } }); return Array.from(languageMap.values()).sort((a, b) => { if (!a.code || !b.code) return 0; return a.code.localeCompare(b.code); }); }; exports.getLanguages = getLanguages; const getCountriesByLanguages = (languageCodes) => { return countries_1.countries.filter(country => country.language && languageCodes.includes(country.language.code)); }; exports.getCountriesByLanguages = getCountriesByLanguages; // Validation utilities const isValidCountryCode = (code) => { return countries_1.countries.some(country => country.code === code); }; exports.isValidCountryCode = isValidCountryCode; const isValidCurrencyCode = (code) => { return countries_1.countries.some(country => country.currency.code === code); }; exports.isValidCurrencyCode = isValidCurrencyCode; const isValidPhoneCode = (phoneCode) => { return countries_1.countries.some(country => country.countryCode === phoneCode); }; exports.isValidPhoneCode = isValidPhoneCode; // Formatting utilities const formatCountryName = (code, format = 'full') => { const country = (0, exports.getByCode)(code); if (!country) return undefined; if (format === 'full') { return `${country.label} (${country.code})`; } return country.label; }; exports.formatCountryName = formatCountryName; const formatPhoneNumber = (phoneNumber, countryCode) => { const country = (0, exports.getByCode)(countryCode); if (!country) return undefined; const cleanedNumber = phoneNumber.replace(/\D/g, ''); return `${country.countryCode} ${cleanedNumber}`; }; exports.formatPhoneNumber = formatPhoneNumber; // Comparison utilities const compareCountries = (code1, code2) => { var _a, _b; const country1 = (0, exports.getByCode)(code1); const country2 = (0, exports.getByCode)(code2); if (!country1 || !country2) return undefined; return { sameRegion: country1.region === country2.region, sameCurrency: country1.currency.code === country2.currency.code, sameLanguage: ((_a = country1.language) === null || _a === void 0 ? void 0 : _a.code) === ((_b = country2.language) === null || _b === void 0 ? void 0 : _b.code) }; }; exports.compareCountries = compareCountries; // Neighboring countries (by region) const getNeighboringCountries = (code) => { const country = (0, exports.getByCode)(code); if (!country) return []; return countries_1.countries.filter(c => c.region === country.region && c.code !== country.code); }; exports.getNeighboringCountries = getNeighboringCountries; // Sort utilities const sortCountriesBy = (field, order = 'asc') => { const sorted = [...countries_1.countries].sort((a, b) => { var _a, _b; let aValue, bValue; if (field === 'currency.code') { aValue = a.currency.code; bValue = b.currency.code; } else if (field === 'language.code') { aValue = ((_a = a.language) === null || _a === void 0 ? void 0 : _a.code) || ''; bValue = ((_b = b.language) === null || _b === void 0 ? void 0 : _b.code) || ''; } else { aValue = a[field]; bValue = b[field]; } if (typeof aValue === 'string' && typeof bValue === 'string') { return order === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue); } return 0; }); return sorted; }; exports.sortCountriesBy = sortCountriesBy; // Random country selector const getRandomCountry = () => { const randomIndex = Math.floor(Math.random() * countries_1.countries.length); return countries_1.countries[randomIndex]; }; exports.getRandomCountry = getRandomCountry; const getRandomCountries = (count) => { const shuffled = [...countries_1.countries].sort(() => 0.5 - Math.random()); return shuffled.slice(0, Math.min(count, countries_1.countries.length)); }; exports.getRandomCountries = getRandomCountries; // Flag utilities const getFlagUrl = (code, size = '48x36') => { const country = (0, exports.getByCode)(code); if (!country) return undefined; return country.flag.replace('48x36', size); }; exports.getFlagUrl = getFlagUrl; // Capital city utilities const getCapitals = () => { return countries_1.countries.map(country => ({ country: country.label, capital: country.capital })).sort((a, b) => a.capital.localeCompare(b.capital)); }; exports.getCapitals = getCapitals; const getCountryByCapital = (capital) => { return countries_1.countries.find(country => country.capital.toLowerCase() === capital.toLowerCase()); }; exports.getCountryByCapital = getCountryByCapital; // ISO code utilities const getByIsoCode = (isoCode) => { return countries_1.countries.find(country => country.isoCode === isoCode); }; exports.getByIsoCode = getByIsoCode; const getIsoCodeMapping = () => { return countries_1.countries.reduce((acc, country) => { acc[country.code] = country.isoCode; return acc; }, {}); }; exports.getIsoCodeMapping = getIsoCodeMapping; const searchCountriesAdvanced = (query, filters) => { let results = (0, exports.searchCountries)(query); if (filters) { if (filters.regions && filters.regions.length > 0) { results = results.filter(country => filters.regions.includes(country.region)); } if (filters.currencies && filters.currencies.length > 0) { results = results.filter(country => filters.currencies.includes(country.currency.code)); } if (filters.languages && filters.languages.length > 0) { results = results.filter(country => country.language && filters.languages.includes(country.language.code)); } if (filters.minPopulation !== undefined) { results = results.filter(country => country.population && country.population >= filters.minPopulation); } if (filters.maxPopulation !== undefined) { results = results.filter(country => country.population && country.population <= filters.maxPopulation); } if (filters.minArea !== undefined) { results = results.filter(country => country.area && country.area >= filters.minArea); } if (filters.maxArea !== undefined) { results = results.filter(country => country.area && country.area <= filters.maxArea); } } return results; }; exports.searchCountriesAdvanced = searchCountriesAdvanced; // Geographical utilities const getCountriesInTimezone = (timezone) => { return countries_1.countries.filter(country => country.timezone && country.timezone.includes(timezone)); }; exports.getCountriesInTimezone = getCountriesInTimezone; const getCountriesByCoordinates = (lat, lng, radiusKm) => { const earthRadiusKm = 6371; return countries_1.countries.filter(country => { if (!country.coordinates) return false; const dLat = toRadians(country.coordinates.latitude - lat); const dLng = toRadians(country.coordinates.longitude - lng); const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRadians(lat)) * Math.cos(toRadians(country.coordinates.latitude)) * Math.sin(dLng / 2) * Math.sin(dLng / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); const distance = earthRadiusKm * c; return distance <= radiusKm; }); }; exports.getCountriesByCoordinates = getCountriesByCoordinates; const toRadians = (degrees) => { return degrees * (Math.PI / 180); }; const getDistanceBetweenCountries = (code1, code2) => { const country1 = (0, exports.getByCode)(code1); const country2 = (0, exports.getByCode)(code2); if (!(country1 === null || country1 === void 0 ? void 0 : country1.coordinates) || !(country2 === null || country2 === void 0 ? void 0 : country2.coordinates)) return undefined; const earthRadiusKm = 6371; const dLat = toRadians(country2.coordinates.latitude - country1.coordinates.latitude); const dLng = toRadians(country2.coordinates.longitude - country1.coordinates.longitude); const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRadians(country1.coordinates.latitude)) * Math.cos(toRadians(country2.coordinates.latitude)) * Math.sin(dLng / 2) * Math.sin(dLng / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return earthRadiusKm * c; }; exports.getDistanceBetweenCountries = getDistanceBetweenCountries; // Border countries utilities const getBorderingCountries = (code) => { const country = (0, exports.getByCode)(code); if (!(country === null || country === void 0 ? void 0 : country.borderCountries)) return []; return country.borderCountries .map(borderCode => (0, exports.getByCode)(borderCode)) .filter((c) => c !== undefined); }; exports.getBorderingCountries = getBorderingCountries; const areBorderingCountries = (code1, code2) => { var _a; const country1 = (0, exports.getByCode)(code1); return ((_a = country1 === null || country1 === void 0 ? void 0 : country1.borderCountries) === null || _a === void 0 ? void 0 : _a.includes(code2)) || false; }; exports.areBorderingCountries = areBorderingCountries; // Population and area utilities const getMostPopulousCountries = (limit = 10) => { return countries_1.countries .filter(country => country.population !== undefined) .sort((a, b) => (b.population || 0) - (a.population || 0)) .slice(0, limit); }; exports.getMostPopulousCountries = getMostPopulousCountries; const getLeastPopulousCountries = (limit = 10) => { return countries_1.countries .filter(country => country.population !== undefined) .sort((a, b) => (a.population || 0) - (b.population || 0)) .slice(0, limit); }; exports.getLeastPopulousCountries = getLeastPopulousCountries; const getLargestCountries = (limit = 10) => { return countries_1.countries .filter(country => country.area !== undefined) .sort((a, b) => (b.area || 0) - (a.area || 0)) .slice(0, limit); }; exports.getLargestCountries = getLargestCountries; const getSmallestCountries = (limit = 10) => { return countries_1.countries .filter(country => country.area !== undefined) .sort((a, b) => (a.area || 0) - (b.area || 0)) .slice(0, limit); }; exports.getSmallestCountries = getSmallestCountries; const getPopulationDensity = (code) => { const country = (0, exports.getByCode)(code); if (!(country === null || country === void 0 ? void 0 : country.population) || !(country === null || country === void 0 ? void 0 : country.area) || country.area === 0) return undefined; return country.population / country.area; }; exports.getPopulationDensity = getPopulationDensity; // Statistical analysis const getCountryStatistics = () => { const stats = { totalCountries: countries_1.countries.length, totalRegions: (0, exports.getRegions)().length, totalCurrencies: (0, exports.getCurrencies)().length, totalLanguages: (0, exports.getLanguages)().length }; const countriesWithPopulation = countries_1.countries.filter(c => c.population !== undefined); const countriesWithArea = countries_1.countries.filter(c => c.area !== undefined); if (countriesWithPopulation.length > 0) { const sortedByPop = [...countriesWithPopulation].sort((a, b) => (b.population || 0) - (a.population || 0)); stats.mostPopulousCountry = sortedByPop[0].label; stats.leastPopulousCountry = sortedByPop[sortedByPop.length - 1].label; } if (countriesWithArea.length > 0) { const sortedByArea = [...countriesWithArea].sort((a, b) => (b.area || 0) - (a.area || 0)); stats.largestCountry = sortedByArea[0].label; stats.smallestCountry = sortedByArea[sortedByArea.length - 1].label; } return stats; }; exports.getCountryStatistics = getCountryStatistics; // Demonym utilities const getByDemonym = (demonym) => { return countries_1.countries.find(country => { var _a; return ((_a = country.demonym) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === demonym.toLowerCase(); }); }; exports.getByDemonym = getByDemonym; const getDemonyms = () => { return countries_1.countries .filter(country => country.demonym) .map(country => ({ country: country.label, demonym: country.demonym })) .sort((a, b) => a.demonym.localeCompare(b.demonym)); }; exports.getDemonyms = getDemonyms; // Native name utilities const getByNativeName = (nativeName) => { return countries_1.countries.find(country => { var _a; return ((_a = country.nativeName) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === nativeName.toLowerCase(); }); }; exports.getByNativeName = getByNativeName; const getNativeNames = () => { return countries_1.countries .filter(country => country.nativeName) .map(country => ({ country: country.label, nativeName: country.nativeName })) .sort((a, b) => a.nativeName.localeCompare(b.nativeName)); }; exports.getNativeNames = getNativeNames; // Subregion utilities const getSubregions = () => { const subregions = new Set(countries_1.countries .filter(country => country.subregion) .map(country => country.subregion)); return Array.from(subregions).sort(); }; exports.getSubregions = getSubregions; const getCountriesBySubregion = (subregion) => { return countries_1.countries.filter(country => country.subregion === subregion); }; exports.getCountriesBySubregion = getCountriesBySubregion; // Export utilities for data analysis const exportCountriesToCSV = () => { const headers = ['Name', 'Code', 'Capital', 'Region', 'Currency Code', 'Currency Name', 'Language Code', 'Phone Code', 'ISO Code']; const rows = countries_1.countries.map(country => { var _a; return [ country.label, country.code, country.capital, country.region, country.currency.code, country.currency.label, ((_a = country.language) === null || _a === void 0 ? void 0 : _a.code) || '', country.countryCode, country.isoCode ]; }); const csvContent = [headers, ...rows] .map(row => row.map(cell => `"${cell}"`).join(',')) .join('\n'); return csvContent; }; exports.exportCountriesToCSV = exportCountriesToCSV; const exportCountriesToJSON = (pretty = true) => { return pretty ? JSON.stringify(countries_1.countries, null, 2) : JSON.stringify(countries_1.countries); }; exports.exportCountriesToJSON = exportCountriesToJSON; // Batch operations const getCountriesBatch = (codes) => { return codes.map(code => (0, exports.getByCode)(code)); }; exports.getCountriesBatch = getCountriesBatch; const validateCountryCodes = (codes) => { const valid = []; const invalid = []; codes.forEach(code => { if ((0, exports.isValidCountryCode)(code)) { valid.push(code); } else { invalid.push(code); } }); return { valid, invalid }; }; exports.validateCountryCodes = validateCountryCodes; // Region name mapping const regionNames = { 'AF': 'Africa', 'AS': 'Asia', 'EU': 'Europe', 'NA': 'North America', 'OC': 'Oceania', 'SA': 'South America', 'AN': 'Antarctica' }; const getRegionName = (regionCode) => { return regionNames[regionCode] || regionCode; }; exports.getRegionName = getRegionName; const getRegionsWithNames = () => { return (0, exports.getRegions)().map(regionCode => ({ code: regionCode, name: (0, exports.getRegionName)(regionCode), countries: (0, exports.getByCodeArea)(regionCode).length })); }; exports.getRegionsWithNames = getRegionsWithNames; // Currency detailed information const getCurrencyDetails = (currencyCode) => { const countriesWithCurrency = (0, exports.getByCurrency)(currencyCode); if (countriesWithCurrency.length === 0) return undefined; const currency = countriesWithCurrency[0].currency; return { code: currency.code, label: currency.label, symbol: currency.symbol, countries: countriesWithCurrency.map(c => c.label) }; }; exports.getCurrencyDetails = getCurrencyDetails; // Language detailed information const getLanguageDetails = (languageCode) => { const countriesWithLanguage = (0, exports.getByLanguage)(languageCode); if (countriesWithLanguage.length === 0) return undefined; const language = countriesWithLanguage[0].language; return { code: language.code, label: language.label, countries: countriesWithLanguage.map(c => c.label) }; }; exports.getLanguageDetails = getLanguageDetails;