Created
September 7, 2016 13:01
-
-
Save aliaksandr-master/aebe57adc7c4c27496591c980007015c to your computer and use it in GitHub Desktop.
tiny translate script
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
'use strict'; | |
let translations = {}; | |
const PLACEHOLDER_EXP = /\{%\s*([^\s%]*)\s*%}/g; | |
const translate = (phrase, params = {}) => { | |
let translation; | |
if (!translations.hasOwnProperty(phrase)) { | |
if (!__PROD_MODE__) { | |
console.warn(`has no translation for "${phrase}"`); // eslint-disable-line no-console | |
} | |
translation = phrase; | |
} else { | |
translation = translations[phrase]; | |
} | |
if (PLACEHOLDER_EXP.test(translation)) { | |
translation = translation.replace(PLACEHOLDER_EXP, ($0, $1) => { | |
if (params.hasOwnProperty($1)) { | |
return params[$1]; | |
} | |
if (!__PROD_MODE__) { | |
console.error(`undefined translation param "${$1}"`); // eslint-disable-line no-console | |
} | |
return ''; | |
}); | |
} | |
return translation; | |
}; | |
translate.configure = (_translations) => { | |
translations = { | |
...translations, | |
_translations | |
}; | |
}; | |
module.exports = translate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment