Skip to content

Instantly share code, notes, and snippets.

@petecleary
Last active December 14, 2015 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petecleary/5063652 to your computer and use it in GitHub Desktop.
Save petecleary/5063652 to your computer and use it in GitHub Desktop.
localizeReader is a function that helps provides a standard way to read a resource based on a culture. It takes the object to find the value for and the culture. It will first look for the specific culture ("de-DE"), then fallback to the neutral culture ("de"), then to a default version, then pick the first in the object. It works for objects as…
var localizeReader = exports;
(function (localizeReader) {
localizeReader.get = function(obj, culture){
var c = (!culture) ? 'default': culture;
if(obj[c] !== undefined) return obj[c];
c = c.split('-')[0];
if(obj[c] !== undefined) return obj[c];
for (var prop in obj) {
return obj[prop];
}
}
})(localizeReader || (localizeReader = {}));
//the object to test must be in the following format - PLEASE NOTE IT IS NOT AN ARRAY
// { "CULTURE", object }
var tests = {
"default": { name: "default", message: "This is the default result" },
"de-DE": { name: "de-DE", message: "This is the specific culture version de-DE" },
"de": { name: "de", message: "This is the neutral culture version de" }
};
//require the function (node.js example)
var localizeReader = require('./localizeReader');
//show specific culture
console.log("show specific culture");
console.log(localizeReader.get(tests, 'de-DE'));
//show neutral culture
console.log("show neutral culture");
console.log(localizeReader.get(tests, 'de'));
//show empty culture
console.log("show empty culture");
console.log(localizeReader.get(tests, ''));
//show null culture
console.log("show null culture");
console.log(localizeReader.get(tests));
//show missing culture
console.log("show missing culture");
console.log(localizeReader.get(tests, 'de-AT'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment