diff options
author | Samy Pessé <samypesse@gmail.com> | 2015-03-09 10:43:12 +0100 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2015-03-09 10:43:12 +0100 |
commit | 34fc2831e0cf0fed01c71cec28d93472d87f455b (patch) | |
tree | a803cc907c20491ba02863b5d3dd5aedf6bfed10 /lib/utils/i18n.js | |
parent | e1594cde2c32e4ff48f6c4eff3d3d461743d74e1 (diff) | |
parent | 1bf68a5aa0703b5a1815cfe4ebb731b5fb6ed9d2 (diff) | |
download | gitbook-34fc2831e0cf0fed01c71cec28d93472d87f455b.zip gitbook-34fc2831e0cf0fed01c71cec28d93472d87f455b.tar.gz gitbook-34fc2831e0cf0fed01c71cec28d93472d87f455b.tar.bz2 |
Merge branch 'version/2.0'
Diffstat (limited to 'lib/utils/i18n.js')
-rw-r--r-- | lib/utils/i18n.js | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/lib/utils/i18n.js b/lib/utils/i18n.js new file mode 100644 index 0000000..d7560bd --- /dev/null +++ b/lib/utils/i18n.js @@ -0,0 +1,72 @@ +var _ = require("lodash"); +var path = require("path"); +var fs = require("fs"); + +var I18N_PATH = path.resolve(__dirname, "../../theme/i18n/") + +var getLocales = _.memoize(function() { + var locales = fs.readdirSync(I18N_PATH); + return _.chain(locales) + .map(function(local) { + local = path.basename(local, ".json"); + return [local, _.extend({ + direction: "ltr" + }, require(path.join(I18N_PATH, local)), { + id: local + })]; + }) + .object() + .value(); +}); + +var getLanguages = function() { + return _.keys(getLocales()); +}; + +var getByLanguage = function(lang) { + lang = normalizeLanguage(lang); + var locales = getLocales(); + return locales[lang]; +}; + +var compareLocales = function(lang, locale) { + var langMain = _.first(lang.split("-")); + var langSecond = _.last(lang.split("-")); + + var localeMain = _.first(locale.split("-")); + var localeSecond = _.last(locale.split("-")); + + if (locale == lang) return 100; + if (localeMain == langMain) return 50; + if (localeSecond == langSecond) return 20; + return 0; +}; + +var normalizeLanguage = _.memoize(function(lang) { + var locales = getLocales(); + var language = _.chain(locales) + .values() + .map(function(locale) { + locale = locale.id; + + return { + locale: locale, + score: compareLocales(lang, locale) + } + }) + .filter(function(lang) { + return lang.score > 0; + }) + .sortBy("score") + .pluck("locale") + .last() + .value(); + return language || lang; +}); + +module.exports = { + getLocales: getLocales, + getLanguages: getLanguages, + getByLanguage: getByLanguage, + normalizeLanguage: normalizeLanguage +}; |