i18n: set locale only once instead of on each call (#3200)

This commit is contained in:
Alexandr Garbuzov
2023-09-12 09:31:11 +02:00
committed by GitHub
parent 8879c7fe2e
commit b611018476
+8 -7
View File
@@ -1,3 +1,5 @@
const FALLBACK_LOCALE = "en";
/**
* I18n translation class.
*/
@@ -10,9 +12,8 @@ class I18n {
* @param {Object} options.translations Translations.
*/
constructor({ locale, translations }) {
this.locale = locale;
this.locale = locale || FALLBACK_LOCALE;
this.translations = translations;
this.fallbackLocale = "en";
}
/**
@@ -22,17 +23,17 @@ class I18n {
* @returns {string} Translated string.
*/
t(str) {
const locale = this.locale || this.fallbackLocale;
if (!this.translations[str]) {
throw new Error(`${str} Translation string not found`);
}
if (!this.translations[str][locale]) {
throw new Error(`'${str}' translation not found for locale '${locale}'`);
if (!this.translations[str][this.locale]) {
throw new Error(
`'${str}' translation not found for locale '${this.locale}'`,
);
}
return this.translations[str][locale];
return this.translations[str][this.locale];
}
}