I have this codewars exercise in which I have to write a piece of code to validate that a supplied string is balanced. For example, I need to make sure when I encounter an opening "("
then I'll have to make sure there's also closing ")"
tag. However, in this code, a second string will contain the parentheses or characters for the first string to find and check.
Here is my code:
function isBalanced(s, caps) {
let strArr = s.split("");
let capsArr = caps.split("");
let pairsCaps = caps.match(/.{1,2}/g);
for(let i = 0; i < strArr.length; i++) {
for (let m = 0; m < pairsCaps.length; m++){
if(strArr[i] == pairsCaps[m][0] && strArr[strArr.length -1] == pairsCaps[m][1]) {
return true;
} else {
return false;
}
}
}
}
console.log(isBalanced("Sensei says -yes-!", "--"));
However, when I ran some sample tests, I found out that while it worked for isBalanced("(Sensei says yes!)", "()")
and isBalanced("(Sensei [says] yes!)", "()[]")
, the code wasn't working when there's --
in isBalanced("Sensei says -yes-!", "--")
in which it returned false
when it was supposed to return true
.
I looked over my code but couldn't narrow down the problem. Please help...?