Created
August 16, 2016 14:53
-
-
Save tomasr8/fc58709116443481bafb9c7515d8e711 to your computer and use it in GitHub Desktop.
parens validator
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
let log = console.log.bind(console); | |
let test1 = "(asf(s)f)jkl(kl)l)l"; | |
let test2 = "(hf)fh()(h(hf()h)gh)fffh"; | |
log(validate(test1)); // --> false | |
log(validate(test2)); // --> true | |
function validate(str) { | |
str = str.replace(/[^\(\)]/g, ""); | |
const lparens = (str.match(/\(/g) || []).length; | |
const rparens = (str.match(/\)/g) || []).length; | |
if(lparens !== rparens) { | |
return false; | |
} | |
let level = 0; | |
for(let i = 0; i < str.length; i++) { | |
if(str[i] === "(") { | |
level++; | |
} else if(str[i] === ")") { | |
level--; | |
} | |
if(level < 0) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment