Skip to content

Instantly share code, notes, and snippets.

@AamuLumi
Created June 22, 2021 10:45
Show Gist options
  • Save AamuLumi/486e0e8e01910259cb7460e4c25c1566 to your computer and use it in GitHub Desktop.
Save AamuLumi/486e0e8e01910259cb7460e4c25c1566 to your computer and use it in GitHub Desktop.
Simple Translator in JS
const FR_FR_TRANSLATIONS = require("./fr-FR.json");
const EN_US_TRANSLATIONS = require("./en-US.json");
class Translator {
constructor() {
this.setLanguage("en-US");
}
setLanguage = (newLang) => {
switch (newLang) {
case "fr-FR":
this.language = "fr-FR";
this.translations = FR_FR_TRANSLATIONS;
break;
case "en-US":
default:
this.language = "en-US";
this.translations = EN_US_TRANSLATIONS;
}
};
_insertArguments = (text, arg) => {
if (!arg) {
return text;
}
return text.replace(/\$\-/g, arg);
};
get = (text, arg) => {
const currentTranslation = this.translations[text.toUpperCase()];
if (!currentTranslation) {
return text;
}
if (typeof currentTranslation === "string") {
return this._insertArguments(currentTranslation, arg);
}
if (arg === undefined || arg === null) {
if (!currentTranslation.null) {
throw new Error(`Cannot find null translation for ${text}`);
}
return currentTranslation.null;
}
if (currentTranslation[String(arg)]) {
return this._insertArguments(currentTranslation[String(arg)], arg);
}
if (!currentTranslation.N) {
throw new Error(`Cannot find N translation for ${text}`);
}
return this._insertArguments(currentTranslation.N, arg);
};
}
const translator = new Translator();
export default translator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment