From e3f0c60777cc325b6434428601b072576e28f0e1 Mon Sep 17 00:00:00 2001 From: Frank Elsinga Date: Sat, 20 Apr 2024 17:41:07 +0200 Subject: [PATCH] Simplifiing the code by turning it into a for-loop --- src/i18n.js | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/i18n.js b/src/i18n.js index 0fa0520a..fd9c460d 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -63,12 +63,22 @@ const rtlLangs = [ "fa", "ar-SY", "ur" ]; * @returns {string} the locale that should be displayed */ export function currentLocale() { - const potentialLocales = [ localStorage.locale, navigator.language, ...navigator.languages ]; - const availableLocales = potentialLocales - .filter(l => !!l) - .map(l => l.split("-")[0] in messages ? l.split("-")[0] : l) - .filter(l => l in messages); - return availableLocales[0] || "en"; + for (const locale of [ localStorage.locale, navigator.language, ...navigator.languages ]) { + // localstorage might not have a value or there might not be a language in `navigator.language` + if (!locale) { + continue + } + if (locale in messages) { + return locale; + } + // some locales are further specified such as "en-US". + // If we only have a generic locale for this, we can use it too + const genericLocale = l.split("-")[0]; + if (genericLocale in messages) { + return genericLocale; + } + } + return "en"; } export const localeDirection = () => {