Created
November 10, 2020 07:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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