Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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));
@sebinsua
Copy link
Author

sebinsua commented Nov 8, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment