Reputation: 51
Noob is looking for help. I have a function that takes a string of braces and check if it follows some rules
"(){}[]" => True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False
Solution is simple: keep adding to result array a left braces till you face a right braces(I add it to an array and then slice them) but when I want to slice or pop 2 last elements of the result array it doesnt work
function validBraces(braces){
return [...braces].map((currentBrace,index) => {
let result = []
if(currentBrace == '{' | currentBrace == '(' | currentBrace == '['){
result += (currentBrace) //If I use push I get as a result [ [], [], etc.]
}
if(currentBrace == ')' | currentBrace == ']' | currentBrace == '}'){
result.slice(0, -2)
}
return result//.length == 0 ? true : false
})
}
How I can slice an array of elements inside this function?
Upvotes: 0
Views: 49
Reputation: 23
Your code is doing as it shoul, it is just that you are returning a mapped array (array.map() returns an array). currentBrace does not carry between iterations, so you are slicing nothing. If you wanted it to be a bool, iterate through the array, like:
function validBraces(str) {
let [open,close,stack]=[['[','{','('],[']','}',')'],""];
for (var i of str) {
//if it is an opening brace
if (['[','{','('].includes(i)) stack+=i;
//if it is a closing and matches the last one in the stack
else if (open.indexOf(stack[stack.length-1])==close.indexOf(i)) {
stack=stack.slice(0,-1);
} else return false;
}
return stack.length==0;
}
Upvotes: 2