Created
May 7, 2015 15:49
-
-
Save syzer/f40ed918cb5102438500 to your computer and use it in GitHub Desktop.
attempt1
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
function match_brackets(str){ | |
var stack = [], | |
lookup = { | |
//key : value pairs | |
'(' : ')', | |
'{' : '}', | |
'[' : ']', | |
}, | |
_keys = Object.keys(lookup), | |
//right = lookup.values | |
_values = Object.keys(lookup).map(function (key) { | |
return lookup[key]; | |
}); | |
str.split("").forEach(function(char){ | |
if (_keys.indexOf(char) > -1){ | |
stack.push(char) | |
} | |
else if( _values.indexOf(char) > -1){ | |
if (stack.length == 0 || (char != lookup[stack[stack.length-1]] )) { | |
return false | |
}else{ | |
lookup[stack.pop()] | |
} | |
} | |
}) | |
return (stack.length == 0) | |
} | |
//tests | |
console.log(match_brackets("{}")) //true | |
console.log(match_brackets("{]")) //false | |
console.log(match_brackets("{{}}")) //true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment