-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-099-substitutingSynonyms-2.js
71 lines (62 loc) · 1.75 KB
/
structy-099-substitutingSynonyms-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
61
62
63
64
65
66
67
68
69
70
71
// p: str , obj
// r:arr
// const sentence = "follow the yellow brick road";
// const synonyms = {
// follow: ["chase", "pursue"],
// yellow: ["gold", "amber", "lemon"],
// };
// substituteSynonyms(sentence, synonyms);
// // [
// // 'chase the gold brick road',
// // 'chase the amber brick road',
// // 'chase the lemon brick road',
// // 'pursue the gold brick road',
// // 'pursue the amber brick road',
// // 'pursue the lemon brick road'
// // ]
// ftgbr []
// / \
// tgbr c p
// | |
// gbr t t
// / \ \ / / \
// g a l g a l
const substituteSynonyms = (str, obj) => {
const arr = str.split(" ");
console.log(arr);
const result = _substitutingSynonyms(obj, arr);
console.log(result);
return result.map((a) => a.join(" "));
};
const _substitutingSynonyms = (obj, arr) => {
if (arr.length === 0) return [[]];
const first = arr[0];
const rest = _substitutingSynonyms(obj, arr.slice(1));
const result = [];
if (first in obj) {
for (let r of rest) {
for (let f of obj[first]) {
result.push([f, ...r]);
}
}
} else {
for (let r of rest) {
result.push([first, ...r]);
}
}
return result;
};
const sentence = "follow the yellow brick road";
const synonyms = {
follow: ["chase", "pursue"],
yellow: ["gold", "amber", "lemon"],
};
console.log(substituteSynonyms(sentence, synonyms));
// [
// 'chase the gold brick road',
// 'chase the amber brick road',
// 'chase the lemon brick road',
// 'pursue the gold brick road',
// 'pursue the amber brick road',
// 'pursue the lemon brick road'
// ]