-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathi18n.ts
47 lines (44 loc) · 1.13 KB
/
i18n.ts
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
let i18n: any = {};
export const flattenObject = (ob: any) => {
const toReturn: any = {};
for (const i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if (typeof ob[i] == "object") {
const flatObject = flattenObject(ob[i]);
for (const x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + "." + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
/**
*
* @param translations
*/
export const setI18N = (translations: any) => {
i18n = flattenObject(translations);
};
/**
* Get a translation from i18n setting
* @param key - Translation key
* @param params - Single term or array of variables
*/
export const translate = (key: string, params?: string | string[]) => {
try {
let term = i18n[key] as string;
if (typeof params === "string") params = [params];
if (params)
params.forEach((param, index) => {
term = term.replace(`$${index + 1}$`, param);
});
if (i18n.helper && typeof i18n.helper === "function")
term = i18n.helper(term);
return term;
} catch (error) {
return "";
}
};