-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-127-tokenReplace-2.js
60 lines (55 loc) · 1.24 KB
/
structy-127-tokenReplace-2.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
// p: obj, str
// r: str
// i
// "the $ADJECTIVE$ fox $VERB$ $ADJECTIVE$ly $DIRECTION$ward",
// j
const tokenReplace = (str, tokens) => {
let i = 0;
let j = 1;
let result = "";
while (i < str.length) {
if (str[i] === "$") {
if (str[j] === "$") {
console.log(i, j);
// str = str.slice(0, i) + tokens[str.slice(i, j + 1)] + str.slice(j + 1);
result += tokens[str.slice(i, j + 1)];
i = j + 1;
j = i + 1;
} else {
j++;
}
} else {
result += str[i];
i++;
j++;
}
}
return result;
};
// const tokens = {
// $LOCATION$: "park",
// $ANIMAL$: "dog",
// };
// // i
// console.log(tokenReplace("Walk the $ANIMAL$ in the $LOCATION$!", tokens));
// // j
// // -> 'Walk the dog in the park!'
// const tokens = {
// $second$: "beta",
// $first$: "alpha",
// $third$: "gamma",
// };
// console.log(tokenReplace("$first$second$third$", tokens));
// // -> 'alphasecondgamma'
const tokens = {
$ADJECTIVE$: "quick",
$VERB$: "hopped",
$DIRECTION$: "North",
};
console.log(
tokenReplace(
"the $ADJECTIVE$ fox $VERB$ $ADJECTIVE$ly $DIRECTION$ward",
tokens
)
);
// -> 'the quick fox hopped quickly Northward'