-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathlocalize.js
55 lines (42 loc) · 1.59 KB
/
localize.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
const moment = require('moment');
const { urlLang } = require('./language');
require('moment/min/locales');
const template = require('./utility').template;
const Localize = (() => {
let localized_texts;
const localizeForLang = (lang) => {
localized_texts = texts_json[lang.toUpperCase()];
moment.locale(lang.toLowerCase());
};
const doLocalize = (txt, params) => {
let text = txt;
const index = text.replace(/[\s|.]/g, '_');
const lang = urlLang().toUpperCase();
const strings = typeof texts_json !== 'undefined' ? texts_json : {};
localized_texts = strings[lang];
text = (localized_texts && localized_texts[index]) || text;
// only use template when explicitly required
return params ? template(text, params) : text;
};
const localize = (text, params) => (
Array.isArray(text) ? text.map(t => doLocalize(t, params)) : doLocalize(text, params)
);
/**
* Localizes the text, but doesn't replace placeholders
* The localized text through this method should replace the placeholders later. e.g. using template()
* @param {String} text - text to be localized
* @return {String} the localized text having the original placeholders ([_1], ...)
*/
const localizeKeepPlaceholders = (text) => (
localize(
text /* localize-ignore */,
[...new Set(text.match(/\[_(\d+)]/g).sort())]
)
);
return {
localize,
localizeKeepPlaceholders,
forLang: localizeForLang,
};
})();
module.exports = Localize;