I'm having trouble understanding how I can traverse between the functions, passing arrays between them, a full day of 'undefined' or 'this is not a function' has me pulling my hair out.
I'm currently doing a challenge on codewars, The task is seemingly simple, take a string that has open and closed braces and check them to see if they're opening/closing in the correct order. However, for some reason the console.log
is not returning anything in this challenge so I'm having to do it blind.
Here's the first function, I set all the variables and the arrays and pass it on to the next function.
function validBraces(braces) {
var braceAr = [];
braceAr = braces.split('');
var testAr = []; // array to be used for testing the order
var i = 0; // iterator for the loop in analyse() function
analyse(...braceAr,...testAr,i); //send the arrays to the function!
}
In the last line in the function above, I'm trying to pass the arrays to the next function, I don't want to create them inside the next function since there is a third function that does the check, sending it back again to the second (analyse). I'm using a spread operator in this 'version', however, I've exhausted my understanding and resources, so I reach out to gain a better understanding. Can someone explain how I can pass these arrays to the functions. I've tried to apply things from explanations I've found but I feel I may be missing something fundamental that is limiting me.
The rest of the code is below, it may not be relevant, but it's there just in case. I'd love to solve this so try to not give too much away ;)
function analyse(braceAr,testAr,i) {
for(l = braceAr.length; i<l ;) {
switch(braceAr[i]) {
case '[':
testAr.push("]");
break;
case '{':
testAr.push("}");
break;
case '(':
testAr.push(")");
break;
case ']':
check(...braceAr,...testAr,i);
break;
case '}':
check(...braceAr,...testAr,i);
break;
case ')':
check(...braceAr,...testAr,i);
break;
} //close switch
} //close loop
return (testAr.length = 0 ? true : false);
} //close function
As you can see, I intend to switch through each element in the array, and if it's an open brace, I'll push the corresponding closing brace into an array to be compared in the third function check()
function check(braceAr,testAr,i) {
if(testAr.pop() === braceAr[i])
{
i++;
analyse(...braceAr,...testAr,i);
} else { return false; }
} //close function
If the most recent element added is the same as the closing brace, we have a matching open/close brace. Increment the index and go back to analysing the rest of the braces.
How does it look?