-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
42 lines (35 loc) · 938 Bytes
/
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
export class Lang {
constructor ({ value = 'en', translations = {} } = {}) {
this.value = value;
this.translations = translations;
}
putTranslations (value, translations) {
this.translations[value] = translations;
}
removeTranslations (value) {
delete this.translations[value];
}
getMessage (message) {
if (!this.translations) {
return message;
}
let messages = this.translations[this.value];
if (!messages) {
return message;
}
return messages[message] || message;
}
interpolate (message, ...args) {
let re = /\{(\d+)\}/g;
let matches;
while ((matches = re.exec(message))) {
let replacement = args[matches[1]] || '';
message = message.replace(matches[0], replacement);
}
return message;
}
translate (message, ...args) {
let translation = this.getMessage(message);
return this.interpolate(translation, ...args);
}
}