Skip to content

Instantly share code, notes, and snippets.

@justinoboyle
Created March 22, 2017 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinoboyle/d1343c0a4c591970408833481e7ec9d4 to your computer and use it in GitHub Desktop.
Save justinoboyle/d1343c0a4c591970408833481e7ec9d4 to your computer and use it in GitHub Desktop.
// 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