From 8cd379c814c0218e77f359476cb4ac491a3e4dc0 Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Mon, 28 Jan 2019 19:15:30 +0100 Subject: [PATCH] Add findBestAvailableLanguage function --- index.d.ts | 4 ++++ index.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/index.d.ts b/index.d.ts index 0418590..dff179e 100644 --- a/index.d.ts +++ b/index.d.ts @@ -30,4 +30,8 @@ declare module "react-native-localize" { type: LocalizationEvent, handler: Function, ): void; + + export function findBestAvailableLanguage( + languageTags: T[], + ): { languageTag: T; isRTL: boolean } | void; } diff --git a/index.js b/index.js index 1266bb0..1fab904 100644 --- a/index.js +++ b/index.js @@ -79,3 +79,38 @@ export function removeEventListener( handlers.delete(handler); } } + +export function findBestAvailableLanguage( + languageTags: string[], +): {| + languageTag: string, + isRTL: boolean, +|} | void { + const locales = getLocales(); + + for (let index = 0; index < locales.length; index++) { + const currentLocale = locales[index]; + const { languageTag, languageCode, isRTL } = currentLocale; + + if (languageTags.includes(languageTag)) { + return { languageTag, isRTL }; + } + + const partialTag = getPartialTag(currentLocale); + const nextLocale = locales[index + 1]; + + if ( + (!nextLocale || partialTag !== getPartialTag(nextLocale)) && + languageTags.includes(partialTag) + ) { + return { languageTag: partialTag, isRTL }; + } + + if ( + (!nextLocale || languageCode !== nextLocale.languageCode) && + languageTags.includes(languageCode) + ) { + return { languageTag: languageCode, isRTL }; + } + } +}