Skip to content

Instantly share code, notes, and snippets.

@ikouchiha47
Last active August 10, 2016 06:40
Show Gist options
  • Save ikouchiha47/385786b9d42cdc3004b082768e5b4262 to your computer and use it in GitHub Desktop.
Save ikouchiha47/385786b9d42cdc3004b082768e5b4262 to your computer and use it in GitHub Desktop.
check string has balenced parenthesis
var stack = [];
var Check = {
isOpen: (str) => ['{', '(', ']'].includes(str),
isClosed: (str) => ['}', ')', ']'].includes(str),
checkClosed: (i, j) => (i == '(' && j == ')') || (i == '{' && j == '}') || (i == '[' && j == ']'),
test: function(str) {
let unb = false;
str.split('').forEach((s) => {
if(this.isOpen(s)) {
stack.push(s);
} else if(this.isClosed(s)) {
let k = stack.pop();
unb = this.checkClosed(k, s);
}
});
return unb;
}
}
var Parenthesis = {
validParentheses: function(data) {
let brackets = '()[]{}'
let Stack = [];
data.split('').forEach(v => {
let bracePosition = brackets.indexOf(v);
if(bracePosition % 2 == 0) {
// if its an opening brace, push the close brace on stack;
Stack.push(bracePosition + 1);
} else {
// check if the closing brace being matched is the one on the top
if(!(Stack.length !== 0 && Stack.pop() === bracePosition)) throw new Error("unbalanced");
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment