Javascript Get Closing Parenthesis
Algorithmic exercise solution to get the closing parenthesis given the opening one.
Solución del ejercicio algorítmico para obtener el paréntesis de cierre dado el paréntesis de apertura.
let parenths = "(()(()))";
function getClosingParenthOf(open) {
let matches = {};
let openParenths = [];
parenths.split("").forEach((parenth, index) => {
if (parenth === "(") {
openParenths.push(index);
}
if (parenth === ")") {
let open = openParenths.pop();
matches[open] = index;
}
});
return matches[open];
}
Usage
console.log(getClosingParenthOf(1)); // 2
console.log(getClosingParenthOf(0)); // 7
console.log(getClosingParenthOf(4)); // 5
console.log(getClosingParenthOf(3)); // 6