Coding Challenge – Bracket Validator

Here is the Question:

Let’s say:

  • ‘(‘, ‘{‘, ‘[‘ are called “openers.”
  • ‘)’, ‘}’, ‘]’ are called “closers.”

Write a function that returns true if an input string’s openers and closers are properly nested.

Examples:

  • “{ ( ) }” should return True
  • “{ ( [ ] ) }” should return True
  • “{ [ ( ] ) }” should return False
 function bracketValidation(input) {
   const openers = ["{", "[", "("];
   const closers = ["}", "]", ")"];
   const match = {
     "}": "{",
     "]": "[",
     ")": "("
   };
   let stack = [];
   for (let i = 0; i < input.length; i++) {
     if (openers.includes(input[i])) {
       lastOpener.push(input[i]);
     }
     if (closers.includes(input[i])) {
       const last = lastOpener.pop();
       if (last !== match[input[i]]) {
         return false;
       }
     }
   }
   return lastOpener.length == 0;
 }

   

Now we also need to provide test cases for the function we have written.

Test Cases:

function testCode(codeoutput, correctoutput) {
  console.log("actual", codeoutput, "expected", correctoutput);
}

testCode(bracketValidation(""), true);
testCode(bracketValidation("{{{}}}"), true);
testCode(bracketValidation("{{{}}}]"), false);
testCode(bracketValidation("{"), false);
testCode(bracketValidation("}"), false);
testCode(bracketValidation("{ [ ] ( { [ ] } ) }"), true);
testCode(bracketValidation("{ [ ] ( { [ ] } ( ) ) }"), true);
testCode(bracketValidation("{ [ () ] ( ) }"), true);
testCode(bracketValidation("{ [ ( ] ) ( ) }"), false);
testCode(bracketValidation("{ [ ] ( ) }"), true);
testCode(bracketValidation("{ [ ( ] ) }"), false);
testCode(bracketValidation("{ [ }"), false);