Last active
October 16, 2017 16:31
-
-
Save nicholasaiello/c088379bcffc4c243b6bc323c76a92f2 to your computer and use it in GitHub Desktop.
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 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