Skip to content

Instantly share code, notes, and snippets.

@stefbowerman
Last active January 2, 2016 10:09
Show Gist options
  • Save stefbowerman/8287999 to your computer and use it in GitHub Desktop.
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.
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