Reputation: 37
I am struggeling with the following problem:
I want to localize an item that offers content in several languages using a fallback strategy which you can see in pseudo code in the code snippet below: how would I go about this in javascript?
// item is a string similar to this below: where some languages are set others are not
// let item = {'en': 'Good morning', 'de': 'Guten Morgen', 'fr': '', 'it': 'Ciao'};
// locale is a language and in ['de', 'fr', 'en', 'it']
let itemLocalize = function (item, locale) {
// return item at locale if it is set
// otherwise return first available language in the order of the array above
}
console.log(itemLocalize(item, 'de')); // 'Guten Morgen'
console.log(itemLocalize(item, 'fr')); // 'Good morning'
console.log(itemLocalize(item, 'it')); // 'Ciao'
console.log(itemLocalize(item, 'en')); // 'Good morning'
Upvotes: 0
Views: 243
Reputation: 1995
You can use something like this. Make changes accordingly
let itemLocalize = function (locale) {
let confirmMessage = {
'en':'Good Morning',
'it':'',
'de':'Guten Morgen',
'fr': ''
}
let arr = ['de', 'fr', 'en', 'it'].find((el) => {
if (el) {
return confirmMessage[el];
}
});
return confirmMessage[locale] || confirmMessage[arr];
}
console.log(itemLocalize('fr'));
console.log(itemLocalize('en'));
console.log(itemLocalize('it'));
console.log(itemLocalize('de'));
Upvotes: 1