Skip to content

Commit 169ac88

Browse files
add: convert string to group
1 parent 93806e8 commit 169ac88

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

convert-string-to-group/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Create function to convert given string to the output below
2+
3+
Input
4+
5+
```console
6+
{1069} AND ({1070} OR {1071} OR {1072}) AND {1244} AND ({1245} OR {1339})
7+
```
8+
9+
Output
10+
11+
```json
12+
{
13+
"AND": [
14+
1069,
15+
{
16+
"OR": [1070, 1071, 1072]
17+
},
18+
1244,
19+
{
20+
"OR": [1245, 1339]
21+
}
22+
]
23+
}
24+
```
25+
26+
## Execute
27+
28+
```bash
29+
node solution.js
30+
```
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const solution = (optionRule) => {
2+
const stack = [];
3+
let currentRule = optionRule;
4+
const groupPattern = /\([^\(\)]+\)/g;
5+
const delimiters = ['OR', 'AND'];
6+
7+
const convert = (groupRule) => {
8+
for (const delimiter of delimiters) {
9+
const regDelimiter = new RegExp(
10+
`[ ]*${delimiter}[ ]*`,
11+
);
12+
if (!regDelimiter.test(groupRule)) {
13+
continue;
14+
}
15+
stack.push({
16+
[delimiter]: groupRule
17+
.split(regDelimiter)
18+
.map((rule) => {
19+
const option = Number(rule.replace(/\D/g, ''));
20+
21+
return (
22+
(/^#\d+#$/.test(rule) && stack[option - 1]) ||
23+
option
24+
);
25+
}),
26+
});
27+
break;
28+
}
29+
};
30+
31+
while (groupPattern.test(currentRule)) {
32+
currentRule = currentRule.replace(
33+
groupPattern,
34+
(match) => {
35+
convert(match.substring(1, match.length - 1));
36+
return `#${stack.length}#`;
37+
},
38+
);
39+
}
40+
41+
convert(currentRule);
42+
43+
return stack.pop();
44+
};
45+
46+
(() => {
47+
console.log(
48+
JSON.stringify(
49+
solution(
50+
'{1069} AND ({1070} OR {1071} OR {1072}) AND {1244} AND ({1245} OR {1339})',
51+
),
52+
null,
53+
2,
54+
),
55+
);
56+
})();

0 commit comments

Comments
 (0)