function BracketMatcher(str) { let left = 0; let right = 0; let diff = 0; let mismatched = false; str .replace(/[^\(\)]/gi, '') .split('') .map(bracket => { if (bracket === '(') { diff++; left++; } else if (bracket === ')') { diff--; right++; } if (diff < 0) { mismatched = true; } }); if (mismatched) return 0; return left === right ? 1 : 0; }