-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpolation.js
55 lines (44 loc) · 1.29 KB
/
interpolation.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
// ref: https://bigfrontend.dev/problem/interpolation
/**
* @param {string} translation
* @param {any} data
* @returns {string}
*/
function t(str, data = {}) {
const length = str.length;
let out = str;
for (let i = 0; i < length;) {
if (str[i] === "{" && str[i + 1] === "{") {
let j = i + 2;
while (str[j] !== "}" && j < length) j++;
if (str[j] === "}" && str[j + 1] === "}") {
const startIdx = i + 2;
const endIdx = j - 1;
const key = str.substring(startIdx, endIdx + 1);
out = out.replace(`{{${key}}}`, data[key] || "");
i = endIdx;
}
}
i++;
}
return out;
}
console.log(t(
"BFE.dev is {{evaluation}}",
{ evaluation: 'fantastic' }
));
console.log(t(
'{{website}} {{verb}} {{evaluation}} {{period}}',
{ website: 'BFE.dev', verb: 'is', evaluation: 'cool', period: '.' }
)); //.toBe('BFE.dev is cool .')
console.log(t(
'{{website}} {{verb}} {{evaluation}} {{period}} ',
)); //.toBe(' '
console.log(t(
'BFE.dev is {{}}{{}}{{}}{{evaluation',
{ evaluation: 'cool' }
)); //.toBe('BFE.dev is {{evaluation')
console.log(t(
'BFE.dev is {{evaluation}}}',
{ evaluation: 'cool' }
)); //.toBe('BFE.dev is cool}')