Skip to content

Commit 0b8f3d3

Browse files
feat: add parseNestedBrackets (#79)
1 parent 75ed75e commit 0b8f3d3

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

other/parse_nested_brackets.ts

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @function parseNestedBrackets
3+
* @description Parse nested brackets algorithm for a string.
4+
* @param {string} text - text to parse
5+
* @param {string} openBrackets - open brackets
6+
* @param {string} closingBrackets - closing brackets
7+
* @returns {string[]} - array of the tags
8+
* @example parseNestedBrackets(`<MAIN hoge><MAIN2 fuga>`) => [ '<MAIN hoge>', '<MAIN2 fuga>' ]
9+
* @example parseNestedBrackets(
10+
* `THIS IS SAMPLE TEXT(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))`,
11+
* { openBrackets: '(', closingBrackets: ')' }) =>
12+
* [
13+
'(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))',
14+
'(ITEM fuga hoge)',
15+
'(ITEM2 nogami(ABBR))',
16+
'(ABBR)'
17+
]
18+
*/
19+
export const parseNestedBrackets = (
20+
text: string,
21+
openBrackets = "<",
22+
closingBrackets = ">"
23+
) => {
24+
let array: string[] = []; // The array of the tags in this present floor.
25+
let prFloor = 0; // The present floor.
26+
let begin = 0, // The begin index of the tag.
27+
end = 0; // The end index of the tag.
28+
for (let i = 0; i < text.length; i++) {
29+
if (text[i] === openBrackets) {
30+
prFloor++;
31+
if (prFloor === 1) begin = i;
32+
} else if (text[i] === closingBrackets) {
33+
if (prFloor === 1) {
34+
end = i;
35+
const tag = text.slice(begin + 1, end);
36+
// push the tag in this present floor.
37+
array.push(`${openBrackets}${tag}${closingBrackets}`);
38+
// push the array of the tags in the next floor.
39+
array = array.concat(
40+
parseNestedBrackets(tag, openBrackets, closingBrackets)
41+
);
42+
}
43+
prFloor--;
44+
}
45+
}
46+
return array;
47+
};
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { parseNestedBrackets } from "../parse_nested_brackets";
2+
3+
describe("parseNestedBrackets", () => {
4+
it("should return an array of the tags", () => {
5+
expect(parseNestedBrackets("<MAIN hoge><MAIN2 fuga>")).toEqual([
6+
"<MAIN hoge>",
7+
"<MAIN2 fuga>",
8+
]);
9+
});
10+
it("should return an array of the tags (nested)", () => {
11+
expect(
12+
parseNestedBrackets(
13+
`THIS IS SAMPLE TEXT(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))`,
14+
"(",
15+
")"
16+
)
17+
).toEqual([
18+
"(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))",
19+
"(ITEM fuga hoge)",
20+
"(ITEM2 nogami(ABBR))",
21+
"(ABBR)",
22+
]);
23+
});
24+
});

0 commit comments

Comments
 (0)