Skip to content

Instantly share code, notes, and snippets.

@1995navinkumar
Last active August 27, 2019 07:32
Show Gist options
  • Select an option

  • Save 1995navinkumar/8876a743a43d599dc58cf232bfc4689b to your computer and use it in GitHub Desktop.

Select an option

Save 1995navinkumar/8876a743a43d599dc58cf232bfc4689b to your computer and use it in GitHub Desktop.
Simple internationalization handling with dynamic values support
/**
* @author navinkumar.c
* @email 1995navinkumar@gmail.com
* @create date 2018-11-01 12:37:56
* @modify date 2018-11-01 12:37:56
* @desc [Internationalization with dynamic values support]
*/
var I18N = (function I18N(){
var entries = {};
function addEntries(hash) {
Object.assign(entries,hash);
}
function get(key, placeHolders) {
let msg = entries[key] || key;
if (placeHolders && typeof placeHolders == "object" && Object.keys(placeHolders).length > 0) {
if (Array.isArray(placeHolders)) {
return placeHolders.reduce((acc, placeHolder, index) => {
return acc.replace(`{${index}}`, placeHolder);
}, msg);
} else {
let holders = Object.keys(placeHolders);
return holders.reduce((acc, ph) => {
return acc.replace(`{${ph}}`, placeHolders[ph]);
}, msg);
}
} else {
return msg;
}
}
return {
addEntries,
get
}
})();
/*
Usage :
Load a particular locale using I18N.addEntries(locale);
var en_US_locales = {
"common.person.name" : "My name is {name}",
"common.person.description" : "Person Description",
"common.person.hobbies" : "My hobbies are {0},{1}"
};
I18N.addEntries(en_US_locales); // we can add as many entries we want during run time
To get a locale value use
I18N.get("common.person.description"); // Will return "Person description"
I18N.get("common.person.name",{name : "Clint Eastwood"}); // Will return "My name is Client Eastwood"
I18N.get("common.person.hobbies",["bounty killing","shooting"]); // Will return "My hobbies are bounty killing,shooting
I18N.get("common.person.age"); // Will return "common.person.age" if none matches
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment