Skip to content

Commit

Permalink
Add findBestAvailableLanguage function
Browse files Browse the repository at this point in the history
  • Loading branch information
zoontek committed Jan 28, 2019
1 parent 3af4fee commit 8cd379c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,8 @@ declare module "react-native-localize" {
type: LocalizationEvent,
handler: Function,
): void;

export function findBestAvailableLanguage<T extends string>(
languageTags: T[],
): { languageTag: T; isRTL: boolean } | void;
}
35 changes: 35 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
}
}

0 comments on commit 8cd379c

Please sign in to comment.