Skip to content

Commit

Permalink
add: solution for bracket-matcher🚀
Browse files Browse the repository at this point in the history
  • Loading branch information
james-gates-0212 committed Apr 2, 2024
1 parent beade6d commit 335efcd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions bracket-matcher/README.md
Original file line number Diff line number Diff line change
@@ -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
```
18 changes: 18 additions & 0 deletions bracket-matcher/solution.js
Original file line number Diff line number Diff line change
@@ -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));
});
})();

0 comments on commit 335efcd

Please # to comment.