Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
});
})();