Skip to content

Instantly share code, notes, and snippets.

@Gosilama
Created February 7, 2020 10:53
Show Gist options
  • Save Gosilama/6844042d6440cf6fea40a3a3ccb71df9 to your computer and use it in GitHub Desktop.
Save Gosilama/6844042d6440cf6fea40a3a3ccb71df9 to your computer and use it in GitHub Desktop.
Check if a string of parenthesis has balanced parenthesis
const parenthesis = {
brace: ['(', ')'],
square: ['[', ']'],
curly: ['{', '}']
};
const parensKeys = Object.keys(parenthesis);
const isOpenParenthesis = (p) => {
for (let i = 0; i < parensKeys.length; i++) {
if (p === parenthesis[`${parensKeys[i]}`][0]) {
return true;
}
}
return false;
}
const parenthesisMatch = (closedParenthesis, openParenthesis) => {
for (let i = 0; i < parensKeys.length; i++) {
if (openParenthesis === parenthesis[`${parensKeys[i]}`][0] && closedParenthesis === parenthesis[`${parensKeys[i]}`][1]) {
return true;
}
}
return false;
}
const isParenthesisBalanced = (str) => {
const strArr = str.split('');
const parenStack = [];
for (let i = 0; i < strArr.length; i++) {
const s = strArr[i];
if (isOpenParenthesis(s)) parenStack.push(s);
else if (parenStack.length === 0 || !parenthesisMatch(s, parenStack.pop())) return false;
}
return parenStack.length === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment