Last active
January 2, 2016 10:09
-
-
Save stefbowerman/8287999 to your computer and use it in GitHub Desktop.
Prototype method to check if a string is balanced in terms of opening and closing parentheses.
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
String.prototype.isBalanced = -> | |
parens = this.match( /[()]/g ) | |
return false unless parens? | |
openStarted = false | |
closureBalance = 0 | |
for i in [0...parens.length] by 1 | |
char = parens[i] | |
if openStarted | |
if char == "(" then closureBalance++ else closureBalance-- | |
else | |
if char == "(" | |
openStarted = true | |
closureBalance++ | |
return false if closureBalance < 0 | |
return closureBalance is 0 | |
examples = [ | |
{ | |
string : '(x(x)' | |
expectation : false | |
}, | |
{ | |
string : ')(x(x)' | |
expectation : false | |
}, | |
{ | |
string : ')(x(x)x)' | |
expectation : true | |
}, | |
{ | |
string : '(x)(x))x()' | |
expectation : false | |
}, | |
{ | |
string : '((x)(x))x()' | |
expectation : true | |
}, | |
] | |
for i in [0...examples.length] by 1 | |
ex = examples[i] | |
console.log ex.string.isBalanced() == ex.expectation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment