-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (69 loc) · 2.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// index.js
/* eslint no-unused-vars: "off" */
const __ = {
defaultsDeep: require('lodash.defaultsdeep'),
forEach: require('lodash.foreach'),
get: require('lodash.get'),
isNil: require('lodash.isnil'),
merge: require('lodash.merge'),
};
class Localize {
constructor(dictionaries, defaultLang) {
const defaults = { en: { __MissingDefaultLang: 'Selected default language is unavailable.' } };
if (typeof dictionaries !== 'object') {
dictionaries = {};
}
this.dictionaries = __.defaultsDeep(dictionaries, defaults);
defaultLang = this.sanitizeLanguageCode(defaultLang);
this.setDefaultLanguage(defaultLang);
}
isLanguageAvailable(lang) {
return this.dictionaries.hasOwnProperty(lang);
}
sanitizeLanguageCode(lang) {
if (typeof lang === 'string') {
return lang.substring(0, 2);
}
return 'en';
}
setDefaultLanguage(lang) {
// Strip region from the langauge code
lang = this.sanitizeLanguageCode(lang);
if (this.isLanguageAvailable(lang)) {
this.defaultLang = lang;
} else {
throw new Error(this.tr('__MissingDefaultLang'));
}
}
listLanguages() {
return Object.keys(this.dictionaries);
}
loadDictionary(lang, dictionary) {
lang = this.sanitizeLanguageCode(lang);
if (!this.dictionaries[lang]) {
this.dictionaries[lang] = {};
}
this.dictionaries[lang] = __.merge(this.dictionaries[lang], dictionary);
}
tr(key, lang, ...params) {
lang = this.sanitizeLanguageCode(lang);
lang = lang || this.defaultLang;
// If the language isn't availabe revert to the default language
if (!this.isLanguageAvailable(lang)) {
lang = this.defaultLang;
}
// Supports nested properties
let retVal = __.get(this.dictionaries[lang], key);
if (__.isNil(retVal)) {
return null;
}
// Replace '$1', '$2', ... in translated text with passed parameters
if (typeof retVal === 'string') {
__.forEach(params, (val, idx) => {
retVal = retVal.replace(`$${idx + 1}`, val);
});
}
return retVal;
}
}
module.exports = Localize;