@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
102 lines (83 loc) • 2.87 kB
text/typescript
/**
* Tools to convert locale, to ISO639-1 native or English
* Resources:
* https://en.wikipedia.org/wiki/ISO_639-1
* https://tools.ietf.org/html/rfc4646
* https://tools.ietf.org/html/rfc4647
* https://github.com/meikidd/iso-639-1
*/
import * as R from "ramda";
import { LANGUAGES } from "./const";
type Languages = {
[code: string]: {
code: string;
name: string;
nativeName: string;
};
};
type LanguageCode = string;
type LanguageName = Languages["code"]["name"];
type LanguageNativeName = Languages["code"]["nativeName"];
/**
* Ensures that the language code exists in the LANGUAGES object
* Using ramda because of the no-prototype-builtins rule we have
*/
export function validate(code: LanguageCode): boolean {
return R.has(code, LANGUAGES);
}
/**
* Takes an RFC 4646 language code and converts it to ISO639-1
* For example: en-GB to en
*/
export function convertToIso(code: LanguageCode): LanguageCode {
if (code && typeof code === "string") {
const isoCode = R.compose(
R.toLower,
R.when(R.is(Array), R.head),
R.split(/([-._])/)
)(code);
return validate(isoCode) ? isoCode : null;
}
return null;
}
/**
* Takes the locale code and returns the corresponding language, written in their native language
* This method, always returns a value, either the name or the code you originally sent
*/
export function getNativeName(code: LanguageCode): LanguageNativeName {
const validCode = convertToIso(code);
return validCode ? LANGUAGES[validCode].nativeName : code;
}
/**
* Takes the locale code and returns the corresponding language, written in English
* This method, always returns a value, either the name or the code you originally sent
*/
export function getName(code: LanguageCode): LanguageName {
const validCode = convertToIso(code);
return validCode ? LANGUAGES[validCode].name : code;
}
/**
* Takes a string name, either in their native language or in English and returns code
* This method, returns an empty string if it does not find the language
* This method, also strips locale specific accents when it runs toLowerCase()
*/
export function getCode(name: LanguageName): LanguageCode | string {
const codes = Object.keys(LANGUAGES);
const code = codes.find((languageCode) => {
const englishLang = LANGUAGES[languageCode].name.toLowerCase();
const nativeLang = LANGUAGES[languageCode].nativeName.toLowerCase();
return (
englishLang === name.toLowerCase() || nativeLang === name.toLowerCase()
);
});
return code || "";
}
export function getAllNativeNames(): LanguageNativeName[] {
return Object.values(LANGUAGES).map((l) => l.nativeName);
}
export function getAllNames(): LanguageName[] {
return Object.values(LANGUAGES).map((l) => l.name);
}
export function getAllCodes(): string[] {
return Object.keys(LANGUAGES);
}