Skip to content

Instantly share code, notes, and snippets.

@nicholasaiello
Last active October 16, 2017 16:31
Show Gist options
  • Save nicholasaiello/c088379bcffc4c243b6bc323c76a92f2 to your computer and use it in GitHub Desktop.
Save nicholasaiello/c088379bcffc4c243b6bc323c76a92f2 to your computer and use it in GitHub Desktop.
function checkBalanced(str, openChar = '(', closeChar = ')') {
// validate input
if (!str || !str.trim().length) {
return false;
}
const matches = str.match(new RegExp(`(\\${openChar}|\\${closeChar})`, 'g'));
// check for odd #
if (matches.length % 2 !== 0) {
return false;
}
let count = 0;
for (let i = 0; i < matches.length; i++) {
const ch = matches[i];
if (ch == openChar) {
count++;
} else {
count--;
if (count < 0) {
return false;
}
}
}
return count === 0;
}
console.log(checkBalanced(')foo)')); // false
console.log(checkBalanced('(foo) ')); // true
console.log(checkBalanced('(foo) ((bar))')); // true
console.log(checkBalanced('foo) ((bar))')); // false
console.log(checkBalanced('(foo) ((bar)) (')); // false
console.log(checkBalanced('(foo) (bar))')); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment