-
-
Save AamuLumi/486e0e8e01910259cb7460e4c25c1566 to your computer and use it in GitHub Desktop.
Simple Translator in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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