Last active
November 13, 2020 23:50
-
-
Save sebinsua/7365781476bd0ca4c4b68a6089fe7a68 to your computer and use it in GitHub Desktop.
This file contains 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
function isOpeningParantheses(char) { | |
return char === "(" || char === "[" || char === "{" || char === "<"; | |
} | |
function isClosingParantheses(char) { | |
return char === ")" || char === "]" || char === "}" || char === ">"; | |
} | |
function isParantheses(char) { | |
return isOpeningParantheses(char) || isClosingParantheses(char); | |
} | |
const matchingParantheses = { | |
"(": ")", | |
")": "(", | |
"[": "]", | |
"]": "[", | |
"{": "}", | |
"}": "{", | |
"<": ">", | |
">": "<" | |
}; | |
function isMatchingParantheses(p1, p2) { | |
return matchingParantheses[p1] === p2 || matchingParantheses[p2] === p1; | |
} | |
function findIndexOfMatchingParantheses(str, paranthesesIndex) { | |
if (!isParantheses(str[paranthesesIndex])) { | |
throw new Error( | |
`The character at the index ${paranthesesIndex} was not a parantheses, it was a ${str[paranthesesIndex]} instead!` | |
); | |
} | |
const direction = isOpeningParantheses(str[paranthesesIndex]) | |
? "RIGHT" | |
: "LEFT"; | |
const stack = []; | |
for ( | |
let idx = paranthesesIndex; | |
idx >= 0 && idx < str.length; | |
direction === "RIGHT" ? idx++ : idx-- | |
) { | |
let char = str[idx]; | |
if (isMatchingParantheses(char, stack[stack.length - 1])) { | |
stack.pop(); | |
} else if (isParantheses(char)) { | |
stack.push(char); | |
} | |
if (stack.length === 0) { | |
return idx; | |
} | |
} | |
return -1; | |
} | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 1)); | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 3)); | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 8)); | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 12)); | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 27)); | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 4)); | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 26)); | |
console.log(findIndexOfMatchingParantheses("a(b(), c(d(e[idx], f[idx])))", 16)); | |
console.log(findIndexOfMatchingParantheses("(+ 2 (- 4 3) (+ 2 2))", 13)); | |
console.log(findIndexOfMatchingParantheses("(+ 2 (- 4 3) (+ 2 2))", 19)); | |
console.log(findIndexOfMatchingParantheses("new HelloWorld<Value>(5)", 14)); | |
console.log(findIndexOfMatchingParantheses("new HelloWorld<Value>(5)", 20)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: https://codesandbox.io/s/nifty-hill-ekrd3?file=/src/index.js:0-2380