Last active
June 6, 2016 00:45
-
-
Save franvarney/22776beda2187f670a50 to your computer and use it in GitHub Desktop.
Matching Braces (JavaScript)
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
var braces = '{()[()]}'; | |
// var braces = '{()()]}'; | |
// var braces = '('; | |
(function matchingBraces() { | |
if (braces.length === 1) return console.log(false); | |
if (!braces) return console.log(true); | |
var leftBraces = ['{', '(', '[']; | |
var rightBraces = ['}', ')', ']']; | |
var leftMatches = []; | |
for (var char in braces) { | |
var current = braces[char]; | |
if (leftBraces.indexOf(current) > -1) leftMatches.push(current); | |
if (rightBraces.indexOf(current) > -1) { | |
if (!leftMatches) return console.log(false); | |
var last = leftMatches[leftMatches.length - 1]; | |
if (leftBraces.indexOf(last) === rightBraces.indexOf(current)) { | |
leftMatches.pop(); | |
} else { | |
return console.log(false); | |
} | |
} | |
} | |
if (leftMatches.length === 0) return console.log(true); | |
})(braces); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment