
“Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing.”
Read More About How to Create Progress Bar using Javascript
Write a function that, given a sentence like the one above, along with the position of an opening parenthesis, finds the corresponding closing parenthesis.
Example: if the example string above is input with the number 10 (position of the first parenthesis), the output should be 79 (position of the last parenthesis).
We simply walk through the string, starting at our input opening parenthesis position. As we iterate, we keep a count of how many additional “(” we find as open_nested_parens. When we find a “)” we decrement open_nested_parens. If we find a “)” and open_nested_parens is 0, we know that “)” closes our initial “(“, so we return its position.
const matchParan = (sent, indx) => {
let open_nested_parens = 0;
for (let i = indx + 1; i < sent.length; i++) {
if (sent[i] === '(') {
open_nested_parens += 1;
}
else if (sent[i] === ')') {
if (open_nested_parens === 0) {
return i;
}
else {
open_nested_parens -= 1;
}
}
}
return false;
}