Skip to content

Instantly share code, notes, and snippets.

@cziem
Created November 10, 2020 07:54
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 cziem/85e73efb0b675055bc23c8997f484848 to your computer and use it in GitHub Desktop.
Save cziem/85e73efb0b675055bc23c8997f484848 to your computer and use it in GitHub Desktop.
Brace matcher that returns a "YES" or "NO" for a given array item
function braces(values) {
if (values.length === 1) return ["NO"];
const map = {
"(": ")",
"[": "]",
"{": "}"
};
const closing = Object.values(map);
const stack = [];
const final = []
for (let charList of values) {
const result = [];
for (let char of charList) {
if (map[char]) {
stack.push(char);
result.push('YES')
} else if (closing.includes(char) && char !== map[stack.pop()]) {
result.push('NO')
}
}
if (result.length * 2 === charList.length) {
final.push('YES')
} else {
final.push('NO')
}
}
return final;
}
braces(["{}()[]", "{[)}", '(){}', '[{]']);
console.log(braces(["{}()[]", "{[)}", '(){}', '[{]']), 'final result')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment