diff --git a/other/parse_nested_brackets.ts b/other/parse_nested_brackets.ts new file mode 100644 index 00000000..dce1ef37 --- /dev/null +++ b/other/parse_nested_brackets.ts @@ -0,0 +1,47 @@ +/** + * @function parseNestedBrackets + * @description Parse nested brackets algorithm for a string. + * @param {string} text - text to parse + * @param {string} openBrackets - open brackets + * @param {string} closingBrackets - closing brackets + * @returns {string[]} - array of the tags + * @example parseNestedBrackets(`
`) => [ '
', '' ] + * @example parseNestedBrackets( + * `THIS IS SAMPLE TEXT(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))`, + * { openBrackets: '(', closingBrackets: ')' }) => + * [ + '(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))', + '(ITEM fuga hoge)', + '(ITEM2 nogami(ABBR))', + '(ABBR)' + ] + */ + export const parseNestedBrackets = ( + text: string, + openBrackets = "<", + closingBrackets = ">" + ) => { + let array: string[] = []; // The array of the tags in this present floor. + let prFloor = 0; // The present floor. + let begin = 0, // The begin index of the tag. + end = 0; // The end index of the tag. + for (let i = 0; i < text.length; i++) { + if (text[i] === openBrackets) { + prFloor++; + if (prFloor === 1) begin = i; + } else if (text[i] === closingBrackets) { + if (prFloor === 1) { + end = i; + const tag = text.slice(begin + 1, end); + // push the tag in this present floor. + array.push(`${openBrackets}${tag}${closingBrackets}`); + // push the array of the tags in the next floor. + array = array.concat( + parseNestedBrackets(tag, openBrackets, closingBrackets) + ); + } + prFloor--; + } + } + return array; + }; diff --git a/other/test/parse_nested_brackets.test.ts b/other/test/parse_nested_brackets.test.ts new file mode 100644 index 00000000..751e8651 --- /dev/null +++ b/other/test/parse_nested_brackets.test.ts @@ -0,0 +1,24 @@ +import { parseNestedBrackets } from "../parse_nested_brackets"; + +describe("parseNestedBrackets", () => { + it("should return an array of the tags", () => { + expect(parseNestedBrackets("
")).toEqual([ + "
", + "", + ]); + }); + it("should return an array of the tags (nested)", () => { + expect( + parseNestedBrackets( + `THIS IS SAMPLE TEXT(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))`, + "(", + ")" + ) + ).toEqual([ + "(MAIN hoge 0.1 fuga(ITEM fuga hoge)hoge(ITEM2 nogami(ABBR)))", + "(ITEM fuga hoge)", + "(ITEM2 nogami(ABBR))", + "(ABBR)", + ]); + }); +});