The Task
is taken from codewars:
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return
true
if the string is valid, andfalse
if it's invalid.All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces:
()[]{}
.What is considered Valid? A string of braces is considered valid if all braces are matched with the correct brace.
Examples
(){}[]
=>True
([{}])
=>True
(}
=>False
[(])
=>False
[({})](]
=>False
My solution
const areBracesBalanced = brc => {
const brace = Object.freeze({
"(": [],
"[": [],
"{": [],
});
const removeBrace = b => brace[b].splice(-1, 1);
const getLastBraceIndex = b => brace[b][brace[b].length - 1]
const braceExists = b => !brace[b].length;
const isBraceBeforeClosed = (before, current) => braceExists(before) || getLastBraceIndex(before) < getLastBraceIndex(current);
const braceIsBalanced = (b, i) => {
switch (b) {
case "(":
case "[":
case "{":
return brace[b].push(i);
case ")":
return isBraceBeforeClosed("[", "(") &&
isBraceBeforeClosed("{", "(") &&
removeBrace("(");
case "]":
return isBraceBeforeClosed("(", "[") &&
isBraceBeforeClosed("{", "[") &&
removeBrace("[");
case "}":
return isBraceBeforeClosed("(", "{") &&
isBraceBeforeClosed("[", "{") &&
removeBrace("{");
default:
// be a good code...
}
};
return[...brc]
.every(braceIsBalanced) && !Object.values(brace).flat().length;
}