-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #17 from james-gates-0212/16-bracket-matcher
16 bracket matcher
- Loading branch information
Showing
3 changed files
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
}); | ||
})(); |