Given a String of Characters, Decide Whether They Are Balanced or Not
// Examples:
// '()()' - balanced
// '((()))' - balanced
// '((()' - not balanced
// ')(' - not balanced
// ')()(' - not balanced
function balancedParens(string) {
// turn string into an array
// apply reduce method
// add 1 to the counter for '(' and subtract 1 from the counter for ')'
// test for characters other than parens in the string
// in the end if counter is 0, it is balanced.
return !string.split('').reduce((prev, char) => {
if (prev < 0) return prev;
if (char === '(') return ++prev;
if (char === ')') return --prev;
return prev;
}, 0);
}
console.log(balancedParens(')(')); // false
console.log(balancedParens('()()')); // true
Thanks to Stephen Grider.