diff --git a/bracket-matcher/README.md b/bracket-matcher/README.md new file mode 100644 index 0000000..0a217d7 --- /dev/null +++ b/bracket-matcher/README.md @@ -0,0 +1,16 @@ +# Bracket Matcher + +Have the function `BracketMatcher(str)` take the `str` parameter being passed and return `1` if the brackets are correctly matched and each one is accounted for. Otherwise return `0`. For example: if `str` is "(hello (world))", then the output should be `1`, but if `str` is "((hello (world))" the the output should be `0` because the brackets do not correctly match up. Only "(" and ")" will be used as brackets. If `str` contains no brackets return `1`. + +## Examples + +```javascript +BracketMatcher('(hello (world))'); // should == 1 +BracketMatcher('((hello (world))'); // should == 0 +``` + +## Execute + +```bash +node solution.js +``` diff --git a/bracket-matcher/solution.js b/bracket-matcher/solution.js new file mode 100644 index 0000000..ab34c43 --- /dev/null +++ b/bracket-matcher/solution.js @@ -0,0 +1,18 @@ +function BracketMatcher(str) { + if (!str) return 1; + + let opens = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === '(') opens++; + if (str[i] === ')') opens--; + if (opens < 0) return 1; + } + + return opens ? 0 : 1; +} + +(() => { + ['(hello (world))', '((hello (world))', undefined, null].forEach((str) => { + console.log(str, '==', BracketMatcher(str)); + }); +})();