Skip to content

Instantly share code, notes, and snippets.

@tomasr8
Created August 16, 2016 14:53
Show Gist options
  • Save tomasr8/fc58709116443481bafb9c7515d8e711 to your computer and use it in GitHub Desktop.
Save tomasr8/fc58709116443481bafb9c7515d8e711 to your computer and use it in GitHub Desktop.
parens validator
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