-
-
Save brianyang/6d4be6d5b79bb92d20d8860de8347e4d 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