|
| 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 | + }; |
0 commit comments