The function I’m writing has to accomplish the following.
It needs to find all parenthesis in an array and create the correct groupings.
Array examples include
["(", "(", ")", ")"]
["(", "(", ")", "(", ")", ")"]
Eventually there will be numbers nestled in them as well.
["2", "+", "5", "**", "3", "(", "57", "/", "3", ")"]
I’m going through my current code and it’s recursive, but it’s not really doing much except updating the global parenthesisIndexArray. At the moment, I’m just looking for advice on improving the code as well as how can I reliably and consistently say with complete confidence that an opening bracket belongs to a specific closing bracket? Debugging it has been quite fun and I’ve made good progress, but I’m still not able to put it all together just yet.
let parenthesisIndexArray = [];
function recursionBaby(arr, length, balance, openCount, closeCount) {
// Base case
if(balance === 0 && length <= 0) {
if(arr[length] === "(") {
balance--;
openCount++;
parenthesisIndexArray.push({
value: arr[length],
index: length
})
}
else if(arr[length] === ")") {
balance++
closeCount++
parenthesisIndexArray.push({
value: arr[length],
index: length
})
}
else {
console.log("balance didn't change");
}
return parenthesisIndexArray;
}
else {
if(arr[length] === "(") {
balance --;
openCount++;
parenthesisIndexArray.push({
value: arr[length],
index: length
})
}
else if(arr[length] === ")") {
balance++
closeCount++
parenthesisIndexArray.push({
value: arr[length],
index: length
})
}
return recursionBaby(arr, length-1, balance, openCount, closeCount)
}
}