Created
February 15, 2018 01:30
-
-
Save RachelSa/69d7cec2c32b2b25bfa197b1d3318324 to your computer and use it in GitHub Desktop.
checks that brackets are properly closed, in order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function bracketChecker(str){ | |
let match = {"}":"{", "]":"[", ")":"("} | |
let opening = ["(", "[", "{"] | |
let toClose = [] | |
for (let i = 0; i < str.length; i++){ | |
if (opening.includes(str[i])){ | |
toClose.push(str[i]) | |
} else { | |
if (toClose[toClose.length-1] !== match[str[i]]){ | |
return false | |
} else { | |
toClose.pop() | |
} | |
} | |
} | |
return true | |
} | |
console.log(bracketChecker("()({[()()]})")) //true | |
console.log(bracketChecker("()({[(()])})")) //false, mismatch open-close | |
console.log(bracketChecker("()({[()()])")) //false, mismatch count | |
console.log(bracketChecker("(({[()()])")) //false | |
console.log(bracketChecker("[({})]")) //true | |
console.log(bracketChecker("[({}])]")) //false | |
console.log(bracketChecker("[]()[]"))//true | |
console.log(bracketChecker("[}]{}"))//false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment