iso-locale-tools
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

iso-locale-tools

All world countries and data points about them, as well as tools for interfacing with that data.

Installation

Install with npm or yarn.

npm install iso-locale-tools
yarn add iso-locale-tools

Usage

The full JSON array of all world countries and information about them lives in src/data/countries-expanded.json.

Each country is represented as an object.

  • name
    • common: common name (in English)
    • official: officially recognized name (in English)
    • native: list of names in the country's recognized languages
      • [key: ISO_639_3]: ISO 639-3 language code
        • common: common name (in native language)
        • official: officially recognized name (in native language)
    • alternates: array of alternate name spellings
  • flag: unicode string flag
  • cca2: ISO 3166-1 alpha-2 code
  • cca3: ISO 3166-1 alpha-3 code
  • ccn3: ISO 3166-1 numeric code
  • ioc: International Olympic Committee code
  • governance
    • isSovereign: whether or not the country is independent (i.e. is self-governing)
    • governingBody: the country that governs the dependency (undefined if isSovereign is true)
    • isUNMember: whether or not the country is a member of the UN (undefined if isSovereign is false)
    • isEU: (european countries only) whether or not the country is a member of the EU
    • isSchengen: (european countries only) whether or not the country is a member of the Schengen Area
    • isEurozone: (european countries only) whether or not the country is a part of the Eurozone, i.e. whether or not they use the Euro currency
  • languages
    • official: an array of officially recognized languages
      • name:
        • common: the name of the language in English
        • native: the name of the language in that language
      • iso639_3: ISO639-3 language code
      • bcp47: BCP47 tag
      • iso14924: ISO15924 script tag
      • iana: array of assigned IANA tags
      • isExtinct: whether or not the language is no longer spoken
      • isSpurious: whether or not the language is spurious, i.e. questioned if it ever existed
    • spoken: list of ISO639-3 language tags of languages spoken in the country, but are not recognized as 'official' languages
  • geography
    • coordinates: numeric coordinates of the center of the country
      • latitude
      • longitude
    • isLandlocked: whether or not the country is landlocked (not bordering the ocean)
    • capitalCity: a list of capital cities
    • landArea: size of the country in km2
    • region: the region the country is in (e.g. 'americas', 'europe')
    • subregion: the subregion of the country (e.g. carribbean)
    • borderCountries: list of countries by their ISO 3166-1 alpha-3 codes that border the country
  • locale
    • ietf: a list of IETF locale codes (e.g. en-US)
    • measurementSystem: system of measurement in use
    • drivingSide: driving side
    • hourClock: type of clock used
    • timezones: list of tz database timezones
      • name: name of timezone
      • type: the type of timezone (primary or alias)
      • linkedTo: (if alias) the primary timezone this timezone links to
      • utcOffset: hours offset from UTC
      • dstOffset: hours offset from UTC during DST (if country doesn't observe DST, this is the same value as UTC offset)
    • dateFormats: date formats for each IETF locale
      • key is the IETF locale name
      • value is the date format, where:
        • G = era
        • y = year
        • M = month
        • d = day
    • weekStartsOn: which day is the first day of the week on the calendar
    • distanceUnit: the unit of distance used (kilometer or mile)
    • temperatureMeasurement: the unit of temperature (celsius or fahrenheit)
  • currencies: list of accepted currencies
    • name: official currency name (in English)
    • shortName: the name of the currency itself (e.g. 'dollar' as opposed to 'US Dollar')
    • iso4217: ISO 4217 code
    • isoNumeric: ISO 4217 numeric code
    • symbol: unicode symbol (e.g. '$')
    • subunit: subunit to whole value (e.g. 'cent')
    • subunitToUnit: number of subunits to reach a whole unit value (e.g. 100 cents = 1 dollar)
    • prefix: symbol that prefixes a currency amount (e.g. '$1')
    • suffix: symbol that suffixes a currency amonut (e.g. '1€')
    • decimalMark: symbol that denotes a decimal place
    • decimalPlaces: number of decimal places rounded to
    • thousansSeparator: symbol to denote thousands separation
  • tld: list of top-level domains used
  • idd: international dialing direct info
    • prefix: geographical code prefix (e.g. +1 for US)
    • suffixes: list of suffixes assigned (e.g. 201 in US)
    • callingCodes: list of calling codes (combinations of the prefix and each suffix - e.g. +1201)
  • subdivisions: list of ISO 3166-2 subdivisions of each country
    • name: name of the subdivision in the country's recognized languages
      • [key: ISO_639_3]: ISO 639-3 language code
        • official: official subdivison name
        • common: locally used name variant
        • native: official name in non-alphanumeric script language (e.g. arabic, cyrillic)

There is also a truncated list (src/data/countries.json) that abbreviates and filters out certain data to reduce file size.

Full country list vs. truncated country list

Object countries-expanded.json countries.json
languages.official A list of full language objects A list of ISO639-3 language codes
currencies A list of full currency objects A list of ISO4217 currency codes
locale.timezones A list of full timezone objects A list of tz database timezone names
subdivisions A list of subdivision objects undefined

Note: subdivisions is removed from countries.json because for most countries, it's a huge list and many times isn't needed.

API

This package contains datasets for multiple different things related to world countries. The datasets can be found in src/data/.

import { 
  countriesExpanded, // full countries list
  countries, // truncated country list
  currencies, // world currencies list
  languages, // world languages list
  timezones, // tz database timezones list
} from 'iso-locale-tools'

Types

There are several types and enumerators to assist in handling different ISO codes.

Countries

// ISO3166-1 alpha2 (cca2) codes
enum ISO3166_1_Alpha2 {}
ISO3166_1_Alpha2.AX // "AX"

// ISO3166-1 alpha2 codes keyed by country name
enum ISO3166_1_Alpha2ByCountry {} 
ISO3166_1_Alpha2ByCountry.denmark // "DK"

// ISO3166-1 alpha3 (cca3) codes
enum ISO3166_1_Alpha3 {}
ISO3166_1_Alpha3.ALA // "ALA"

// ISO3166-1 alpha3 codes keyed by country name
enum ISO3166_1_Alpha3ByCountry {}
ISO3166_1_Alpha3ByCountry.denmark // "DNK" 

// ISO3166 numeric (ccn3) codes
enum ISO3166_1_NumericByCountry {}
ISO3166_1_NumericByCountry.british_virgin_islands // "092"

// ISO3166-2 subdivision codes
enum ISO3166_2 {} // ISO3166-2 subdivision codes
ISO3166_2.BT_42 // "BT-42"

Currency

// currency object type
type Currency = {
  name: CurrencyNamesByISO4217 | string
  shortName: CurrencyNamesByISO4217
  iso_4217: ISO4217
  symbol: CurrencySymbolsByISO4217 | string
  subunit: string | null
  subunitToUnit: number | null
  prefix: string | null
  suffix: string | null
  decimalMark: string | null
  decimalPlaces: number | null
  thousandsSeparator: string | null
}

// ISO4217 currency codes
enum ISO4217 {}
ISO4217.USD // "USD"

// currency names by ISO4217 codes
enum CurrencyNamesByISO4217 {}
CurrencyNamesByISO4217.USD // "United States Dollar"

// currency 'short' names by ISO4217
enum CurrencyShortNamesByISO4217 {}
CurrencyShortNamesByISO4217.USD // "dollar"

// currency symbols by ISO4217
enum CurrencySymbolsByISO4217 {}
CurrencySymbolsByISO4217.USD // "$"

Language

type Language = {
  name: {
    common: string
    native: string | null
    alternates?: string[]
  },
  iso639_3: ISO639_3,
  bcp47: BCP47,
  iso15924: ISO15924
  iana: string[]
  countries?: ISO3166_1_Alpha2
  isExtinct: boolean
  isSpurious: boolean
}

// ISO639-3 language codes
enum ISO639_3 {}
ISO639_3.eng // "eng"

// BCP47 language tags
enum BCP47 {}
BCP47.abq_Cyrl // "abq-Cyrl"

// ISO15924 codes
enum ISO15924 {}
ISO15924.cyrl //

Locale

type Locale = {
  ietf: IETF[]
  drivingSide: DrivingSide | DrivingSides
  measurementSystem: MeasurementSystem | MeasurementSystems
  hourClock: HourClock | HourClocks
  timezones: Timezone[] | TZTimezones[]
  dateFormats: {
    [key in IETF]: string
  }
  weekStartsOn: WeekStartDay | WeekStartDays
  distanceUnit: DistanceUnit | DistanceUnits
  temperatureUnit: TemperatureUnit | TemperatureUnit
}

// distance unit -- can use either the type or the enum
type DistanceUnit = "kilometer" | "mile"
enum DistanceUnits {
  KM = "kilometer",
  MI = "mile"
}

// temp unit -- can use either the type or the enum
type TemperatureUnit = "celsius" | "fahrenheit"
enum TemperatureUnits {
  C = "celsius",
  F = "fahrenheit"
}

// week start day -- can use either the type or the enum
type WeekStartDay = "friday" | "saturday" | "sunday" | "monday"
enum WeekStartDays {
  FRIDAY = "friday",
  SATURDAY = "saturday",
  SUNDAY = "sunday",
  MONDAY = "monday"
}

// driving side -- can use either the type or the enum
type DrivingSide = "left" | "right"
enum DrivingSides {
  LEFT = "left",
  RIGHT = "right"
}

// measurement system -- can use either the type or the enum
type MeasurementSystem = "metric" | "imperial"
enum MeasurementSystems {
  METRIC = "metric",
  IMPERIAL = "imperial"
}

// hour clock -- can use either the type or the enum
type HourClock = "12hr" | "24hr" | "mixed"
enum HourClocks {
  AM_PM = "12hr",
  MILITARY = "24hr",
  MIXED = "mixed"
}

// timezone object
type Timezone = {
  name: Timezones
  type: "canonical" | "link"
  linkedTo: string | null
  utcOffset: string
  dstOffset: string
}

// IETF locale codes
enum IETF {}
IETF.en_CA // "en-CA"

// tz database timezone names
enum TZTimezones {}
TZTimezones.windhoek // "Africa/Windhoek"

Location

type Location = {
  coordinates: Coordinates
  isLandlocked: boolean
  borderCountries: ISO3166_1_Alpha3
  capitalCity: string[]
  landArea: number
  region: Regions
  subregion: Subregions
}

// coordinates object
type Coordinates = {
  latitude: number
  longitude: number
}

// regions
enum Regions {}
Regions.oceania // "oceania"

// subregions
enum Subregions {}
Subregions.australia_new_zealand // "Australia and New Zealand"

Utils

Countries

  • countryNameToKey(name: string): CountryKey: gets the country name key for a country by it's common name (name.common)
  • removeDiacritics(str: string): string: Removes diacritics (accented characters, etc.) from a string
import { countryNameToKey, removeDiacritics } from 'iso-locale-tools'

const countryKey = countryNameToKey("Svalbard and Jan Mayen")
// returns `svalbard_jan_mayen`
const cca2 = ISO3166_1_Alpha2ByCountry[countryKey]
// equivalent to ISO3166_1_Alpha2ByCountry.svalbard_jan_mayen

const aland = removeDiacritics("Åland Islands")
// returns "Aland Islands"

Currency

  • getConversionRate({ from, to }: { from: ISO4217, to: ISO4217 }): number | Error: returns the conversion rate between 2 currencies, returns an error if one encountered. This function utilizes the free version of the currconv api.
import { getConversionRate, ISO4217 } from 'iso-locale-tools'

const conversionRate = getConversionRate({
  from: ISO4217.USD,
  to: ISO4217.EUR
})
// returns the conversion rate from the us dollar to euro

Locale

  • convertDistance(distance: number, fromUnit: "kilometer" | "mile"): number: converts a distance from a given unit to the opposite unit
  • getDateFnsLocale(locale: IETF, { fallbackLocale }: { fallbackLocale: DateFnsLocale }): DateFnsLocale: returns a date-fns locale object. if a direct match is not found, it'll try to detect the closest locale, otherwise it uses a fallback. the default fallback is en-US.
  • getDatePatternForLocale(locale: IETF): gets the date format pattern (e.g. 'yyyy-MM-dd') for a given locale
  • getDateTimeForTimezone({ date, dateTimeFormat, timezone, serverTimezone }: { date?: Date | number | string, dateTimeFormat: string, timezone: TZTimezone, serverTimezone?: TZTimezone }): Date: returns a date formatted and converted to a given timezone. if date is not provided, it fallsback to Date.now(). serverTimezone is the timezone to compare against, if necessary (fallback is UTC).
import { 
  convertDistance,
  getDateFnsLocale,
  getDatePatternForLocale, 
  getDateTimeForTimezone 
} from 'iso-locale-tools'

const distance = convertDistance(2, "kilometer")
// returns 1.242742 (miles)

const dateFnsLocaleDirect = getDateFnsLocale("en-AU") // returns the en-AU locale
const dateFnsLocaleClosest = getDateFnsLocale("es-PY") // there is no 'es-PY' locale, so this will return the es locale
const dateFnsLocaleFallback = getDateFnsLocale("aay") // there is no 'aay' locale or a closest match, so this will return the 'en-US' default fallback locale
const dateFnsLocaleFallbackCustom = getDateFnsLocale("aay", { fallbackLocale: "en-CA" }) // will return en-CA as a fallback

const datePattern = getDatePatternForLocale("nl-AW") // returns "dd-MM-yyyy"

const dateTimeInTimezone = getDateTimeForTimezone({
  date: 1636911831222,
  dateTimeFormat: "dd-MM-yyyy HH:mm",
  timezone: "Africa/Windhoek",
})
// returns "14-11-2021 19:44"

Location

  • bearingToDirection(bearing: number): Directions | undefined: converts a bearing (in degrees) to a given cardinal direction
  • getCenterOfCoordinates(coordinates: Coordinates[]): Coordinates: finds the direct center of a group of coordinates
  • getRhumbLine(fromLongitude: number, toLongitude: number): number: gets a rhumb line between 2 longitudes
  • geographicDistanceTo({ from, to, unit, useRhumbLine }: { from: Coordinates, to: Coordinates, unit: DistanceUnit, useRhumbLine?: boolean }): number: get the great-circle distance between 2 points (using haversine formula). set useRhumbLine to true to get the distance between 2 points using a rhumb line.
  • bearingDistanceTo({ from, to, useRhumbLine }: { from: Coordinates, to: Coordinates, useRhumbLine?: boolean }): { initialBearing: number, finalBearing: number}): returns the initial bearing from start point to destination point, and the final bearing which differs by varying degrees according to the lat/long. set useRhumbLine to true to get the bearings over a rhumb line.
import {
  bearingToDirection,
  getCenterOfCoordinates,
  getRhumbLine,
  geographicDistanceTo,
  bearingDistanceTo
} from 'iso-locale-tools'

const direction = bearingToDirection(261)
// returns 'WNW'

const location1 = { latitude: 12.5, longitude: -69.9 }
const location2 = { latitude: 52.5, longitude: 5.75 }

const center = getCenterOfCoordinates([
  location1,
  location2
])
// returns { latitude: 38.44160133305245, longitude: -42.280221828555504 }

const rhumbLine = getRhumbLine(location1.longitude, location2.longitude)
// returns 1.3203415791337105

const distance = geographicDistanceTo({ from: location1, to: location2, unit: "mile" })
// returns 12792.535602738117

const distanceUsingRhumbLine = geographicDistanceTo({ from: location1, to: location2, unit: "kilometer", useRhumbLine: true })
// returns 8156.327629644782

const bearing = bearingDistanceTo({ from: location1, to: location2 })
// returns { initialBearing: 51.51700060782139, finalBearing: 231.5170006078214 }

const bearingUsingRhumbLine = const bearing = bearingDistanceTo({ from: location1, to: location2, useRhumbLine: true })
// returns { initialBearing: 56.90674499795489, finalBearing: 236.9067449979549 }

Acknowledgements

Package Sidebar

Install

npm i iso-locale-tools

Weekly Downloads

662

Version

0.1.1

License

MIT

Unpacked Size

17.9 MB

Total Files

41

Last publish

Collaborators

  • gretzky