Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active November 13, 2020 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebinsua/7365781476bd0ca4c4b68a6089fe7a68 to your computer and use it in GitHub Desktop.
Save sebinsua/7365781476bd0ca4c4b68a6089fe7a68 to your computer and use it in GitHub Desktop.
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