Skip to content

Commit

Permalink
Merge pull request #1 from wp-blocks/languages
Browse files Browse the repository at this point in the history
adds the languages iso to name conversion
  • Loading branch information
erikyo authored Dec 18, 2023
2 parents a35e15b + a4d584c commit ea8c92d
Show file tree
Hide file tree
Showing 29 changed files with 2,772 additions and 2,167 deletions.
95 changes: 88 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ npm install ISOToLanguage

## Usage

Import the module:
Common JS (require):

```javascript
const ITL = require('ISOToLanguage');
Expand All @@ -42,8 +42,11 @@ import { getCountry, getAll } from 'ISOToLanguage';

## Usage

1. **[isValidIso](#isValidIso)**
- Validates ISO codes for languages and countries.
1. **[isValidCountry](#isValidCountry)**
- Validates ISO codes for countries.
-
1. **[isValidLanguage](#isValidLanguage)**
- Validates ISO codes for languages.

2. **[format](#format)**
- Formats language and country into a single string.
Expand Down Expand Up @@ -78,20 +81,34 @@ import { getCountry, getAll } from 'ISOToLanguage';
12. **[getAllLanguageCodesByISO](#getAllLanguageCodesByISO)**
- Retrieves all language codes associated with an array of ISO codes.

## `isValidIso`
## `isValidCountry`

A function that checks if the provided ISO code is valid.

**Args**: `{"iso": "EN"}`
**Args**: `{ "iso": "EN" }`

```javascript
const enIsValid = isValidIso('EN');
const enIsValid = isValidCountry('EN');
console.log(enIsValid); // false

const gbIsValid = isValidIso('GB');
const gbIsValid = isValidCountry('GB');
console.log(gbIsValid); // true
```

## `isValidLanguage`

A function that checks if the provided language is valid.

**Args**: `{ "iso": "en" }`

```javascript
const enIsValid = isValidLanguage('en');
console.log(enIsValid); // true

const gbIsValid = isValidLanguage('gb');
console.log(gbIsValid); // false
```

## `format`

A function that formats the language and country into a single string.
Expand Down Expand Up @@ -165,6 +182,24 @@ console.log(data);
*/
```

## `getLanguage`

Retrieve the ISO language object based on the provided language code.

**Args**: `{ "languageCode" : string }`

```javascript
const data = getCountry('Italia');
console.log(data);

/*
{
"name": "Italian",
"original": "Italiano"
}
*/
```

## `getCountryData`

Get country data by a given locale format (e.g., "en_US").
Expand All @@ -184,6 +219,24 @@ console.log(data);
*/
```

## `getLanguageData`

Retrieve the language data for the specified language code. As getCountryData, accepts two digit language code (e.g. "it") or five (e.g. "it-IT" or "it_IT")

**Args**: `{ "languageCode": string }`

```javascript
const data = getLanguageData( 'it-IT');
console.log(data);

/*
{
"name": "Italian",
"original": "Italiano"
}
*/
```

## `getCountriesByLanguage`

Get all the countries that speak the given languages
Expand Down Expand Up @@ -348,6 +401,34 @@ console.log(countriesData);
*/
```

## `getLanguagesByISO`

This function takes an array of ISO codes and returns a dictionary of languages corresponding to those codes. It iterates over each ISO code and checks if it is a valid language. If it is, the language is added to the result dictionary.

**Args**: `{ "isos": [Array of ISO] }`

```javascript
const countriesData = getLanguagesByISO(['en', 'it', 'es']);
console.log(countriesData);

/*
{
"en": {
"name": "English",
"original": "English"
},
"it": {
"name": "Italian",
"original": "Italiano"
},
"es": {
"name": "Spanish; Castilian",
"original": "español, castellano"
}
}
*/
```

## `getAllLanguagesByISO`

Get the languages from the given array of countries
Expand Down
372 changes: 194 additions & 178 deletions docs/index.html

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"country",
"country code",
"locale format",
"locale format",
"IETF",
"ISO 3166-1",
"language tag"
Expand Down
129 changes: 129 additions & 0 deletions src/asKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import type { Country, CountryData, ISOCode, IsoDataType } from './type'

import { getSeparator } from './utils'
import { format } from './format'
import { isoCountries } from './countries'
import { isoTL } from './iso'
import { getLanguageBy } from './getBy'

/**
* Generates a new object where the keys are derived from the specified `isoData` object's `languages` property.
* The values of the new object are copies of the `isoData` objects with an additional `code` property set to the ISO code.
*
* @param iso - The ISO code for the `isoData` object.
* @param countryData - The `CountryData` object containing language information.
* @private
* @param type - Optional. Specify the type of key to generate. It Can be one of 'locale' or 'language-code'. Defaults to 'locale'.
* @returns A new object with keys derived from the `languages` property and values consisting of copies of `isoData` objects with an additional `code` property.
*/
export function useKey(
iso: ISOCode | string,
countryData: Country,
type?: 'locale' | 'language-code'
): Record<string, CountryData> {
const result: { [key: string]: CountryData } = {}
// Get the separator based on the type
const separator = getSeparator(type)
countryData.languages.forEach((language) => {
// Format the language and country code
const locale = format(language, iso, { separator })
// Add the country data to the result
if (locale) {
result[locale] = { ...countryData, code: iso as ISOCode }
}
})
// Return all the matches
return result
}

/**
* Retrieves country data based on the specified ISO code or string and language type.
*
* @param {ISOCode | string} iso The ISO code or string representing the country.
* @param {Country} countryData The country data object.
* @param {'language' | 'language-name' | 'language-original'} type The type of language to retrieve.
* @returns {Record<string, CountryData>} An object containing the country data for each language key.
*/
export function useLanguageKey(
iso: ISOCode | string,
countryData: Country,
type: 'language' | 'language-name' | 'language-original'
): Record<string, CountryData> {
const result: Record<string, CountryData> = {}
// Add the country data to the result
if (countryData['languages'] instanceof Array) {
countryData.languages.forEach((language) => {
// the language type "language" is already of the type needed (2 digit code)
const key = type === 'language' ? language : getLanguageBy(language, type)
// Add the country data to the result
result[key] = { ...countryData, code: iso as ISOCode }
})
}
// Return all the matches
return result
}

/**
* Generates a new object where the keys are derived from the specified field of each item in the `isoList` object.
* The values of the new object are copies of the corresponding `isoData` objects with an additional `code` property set to the ISO code.
*
* @param type - The field to use as the key for the resulting object. It can be one of 'language', 'name', or 'original'.
* @returns A new object with keys derived from the specified field and values consisting of copies of the corresponding `isoData` objects with an additional `code` property.
*/
export function getAsKey(type: IsoDataType): Record<string, CountryData> {
let result: Record<string, CountryData> = {}

for (const iso in isoCountries) {
const country: Country = isoCountries[iso as ISOCode]
if (type === 'locale' || type === 'language-code') {
const results = useKey(iso as ISOCode, country, type)
result = { ...result, ...results }
} else if (
type === 'language' ||
type === 'language-name' ||
type === 'language-original'
) {
const results = useLanguageKey(iso as ISOCode, country, type)
result = { ...result, ...results }
} else if (type === 'iso') {
result[iso] = { ...country, code: iso as ISOCode }
} else {
const keyValue = country[type]
result[keyValue] = { ...country, code: iso as ISOCode }
}
}

return result
}

/**
* Generates an array of objects suitable for React Select options based on the specified field.
*
* @param {string} key - The field to use as the key for the resulting object. It can be one of 'iso', 'language', 'name', 'original', 'language-code', or 'locale'.
* @param {string} value - The field to use as the value for the resulting object. It can be one of 'iso', 'language', 'name', 'original', 'language-code', or 'locale'.
* @returns {Object[]} An array of objects suitable for React Select options.
*/
export function getKeyValue(key: IsoDataType, value: IsoDataType): { value: string; label: string }[] {
const result = []

for (const iso in isoCountries) {
const keyValue = isoTL(iso as ISOCode, key)
const country = isoTL(iso as ISOCode, value)

if (keyValue instanceof Array) {
keyValue.forEach((item) => {
result.push({
value: item,
label: country.toString(),
})
})
} else {
result.push({
value: keyValue.toString(),
label: country.toString(),
})
}
}

return result
}
Loading

0 comments on commit ea8c92d

Please sign in to comment.