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

This commit is contained in:
Alexandr Garbuzov 2023-09-12 10:31:11 +03:00 committed by GitHub
parent 8879c7fe2e
commit b611018476
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

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];
}
}