Skip to content

Instantly share code, notes, and snippets.

@aliaksandr-master
Created September 7, 2016 13:01
Show Gist options
  • Save aliaksandr-master/aebe57adc7c4c27496591c980007015c to your computer and use it in GitHub Desktop.
Save aliaksandr-master/aebe57adc7c4c27496591c980007015c to your computer and use it in GitHub Desktop.
tiny translate script
'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