Skip to content

Instantly share code, notes, and snippets.

@franvarney
Last active June 6, 2016 00:45
Show Gist options
  • Save franvarney/22776beda2187f670a50 to your computer and use it in GitHub Desktop.
Save franvarney/22776beda2187f670a50 to your computer and use it in GitHub Desktop.
Matching Braces (JavaScript)
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