0

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?

3
  • 1
    array.map() returns an array of all the results of the callback function. So if your function returns an array, the final result will be a 2-dimensional array. Commented Nov 11, 2022 at 23:59
  • Why are you returning the result of .map() if you want the function to return a boolean? Commented Nov 12, 2022 at 0:43
  • @pilchard many more things wrong with the code. It doesn't check whether the currentBrace actually matches the one at the top of the stack, result.slice(0, -2) is not mutating the array, initialising result inside the loop, returning inside of the loop instead of afterwards, the whole usage of map instead of a loop, the name result for the stack, the commented out .length == 0, the unnecessary conditional operator… Commented Nov 12, 2022 at 1:04

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.