Skip to content

Instantly share code, notes, and snippets.

@Alcotana
Created May 28, 2017 14:13
Show Gist options
  • Save Alcotana/d4dd3864be2641122e0f575924dd38ef to your computer and use it in GitHub Desktop.
Save Alcotana/d4dd3864be2641122e0f575924dd38ef to your computer and use it in GitHub Desktop.
A simple example of using ES6 tagged template strings for localization purposes.
var language = 'ru';
//--------------
const langDatabases = {
en: null,
ru: new Map(),
pl: new Map()
}
function strKey(tplArr){
return tplArr.raw.join('$${}');
}
function tran(from, ...toRest){
if(
from.lang !== 'en' ||
toRest.some(to => from.strings.length !== to.strings.length)
){
return false;
}
let fromKey = strKey(from.strings);
toRest.forEach((to) => {
langDatabases[to.lang].set(fromKey, to.strings);
});
return true;
}
const en = strings => ({lang: 'en', strings});
const ru = strings => ({lang: 'ru', strings});
const pl = strings => ({lang: 'pl', strings});
tran(
en`Hello, ${'userName'}! Good to see you.`,
ru`Привет, ${'userName'}! Рады видеть вас.`,
pl`Witam, ${'username'}! Cieszę się, że cię widzę.`,
);
//----------------------
function loc(strings, ...vars){
if(language !== 'en'){
strings = langDatabases[language].get(strKey(strings));
}
return strings.reduce((accumulator, part, i) => {
return accumulator + vars[i - 1] + part
});
}
//----------------------
var userName = 'Ruslan';
console.log('Message (in local)', loc`Hello, ${userName}! Good to see you.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment