Skip to content

Commit

Permalink
Merge pull request #17 from james-gates-0212/16-bracket-matcher
Browse files Browse the repository at this point in the history
16 bracket matcher
  • Loading branch information
james-gates-0212 authored Apr 2, 2024
2 parents beade6d + 56b3f75 commit e7a58a7
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ JavaScript coding assessments are a great way to evaluate coding skills and know
## Table of contents

- [Bracket Combinations](bracket-combinations)
- [Bracket Matcher](bracket-matcher)
- [Calculate the sum of the numbers in a nested array](calculate-the-sum-of-the-numbers-in-a-nested-array)
- [Convert string to group](convert-string-to-group)
- [Delete Overlapping Intervals](delete-overlapping-intervals)
Expand Down
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 e7a58a7

Please sign in to comment.