Created
March 22, 2017 21:58
-
-
Save justinoboyle/d1343c0a4c591970408833481e7ec9d4 to your computer and use it in GitHub Desktop.
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
// Java has this already, don't bother :) | |
Array.prototype.peek = function() { | |
return this[this.length - 1]; | |
} | |
// Cool, right? | |
let toClose = o => o.charCodeAt(0) == 40 ? String.fromCharCode(41) : String.fromCharCode(o.charCodeAt(0) + 2); | |
let toOpen = o => o.charCodeAt(0) == 41 ? String.fromCharCode(40) : String.fromCharCode(o.charCodeAt(0) - 2); | |
let matches = ['(', '[', '{'], | |
closedMatches = matches.map(toClose); | |
// this sucks :( | |
export default function checkBrackets(str) { | |
let stack = []; | |
for (let spot in str) { | |
let char = str[spot], | |
isOpen = matches.indexOf(char) > -1, | |
isClosed = closedMatches.indexOf(char) > -1; | |
let open = isOpen ? char : toOpen(char), | |
closed = isClosed ? char : toClose(char); | |
if(isOpen) | |
stack.push(char) | |
if(isClosed) { | |
let peek = stack.peek(); | |
if(peek == open) | |
stack.pop(); | |
} | |
} | |
return stack.length == 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment