Skip to content

Instantly share code, notes, and snippets.

@RachelSa
Created February 15, 2018 01:30
Show Gist options
  • Save RachelSa/69d7cec2c32b2b25bfa197b1d3318324 to your computer and use it in GitHub Desktop.
Save RachelSa/69d7cec2c32b2b25bfa197b1d3318324 to your computer and use it in GitHub Desktop.
checks that brackets are properly closed, in order
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