Last active
February 25, 2022 22:38
-
-
Save fronterior/c1410230ec2cd3153d83e68ae38498a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bracketParse = str => { | |
let cursor = 0; | |
let depth = 1; | |
const stack = []; | |
const subStack = []; | |
while (cursor < str.length) { | |
const si = str.indexOf('(', cursor); | |
const nsi = str.indexOf('(', si + 1); | |
const ei = str.indexOf(')', cursor); | |
cursor = si; | |
if (si > ei || (si >=0 && ei === -1) || (si === -1 && ei >= 0)) throw 'Invalid braket!'; | |
if (ei === -1) return stack; | |
if (si === -1 || nsi === -1 || nsi > ei) { | |
stack.push({depth, start: si, end: ei}); | |
cursor = ei + 1; | |
while (subStack.length) { | |
const nsi = str.indexOf('(', cursor); | |
const ei = str.indexOf(')', cursor); | |
if (nsi === -1 || nsi > ei) { | |
depth -= 1; | |
const {startIndex: si} = subStack.pop(); | |
stack.push({depth, start: si, end: ei}); | |
cursor = ei + 1; | |
} else { | |
break; | |
} | |
} | |
} else { | |
subStack.push({depth, startIndex: si}); | |
depth += 1; | |
cursor += 1; | |
} | |
} | |
return stack; | |
}; | |
bracketParse('123(te(s(t)(t)e)st)1234'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment