Last active
July 6, 2022 23:01
-
-
Save kylefelipe/63722f3c9eaef68db2d68bb44773f577 to your computer and use it in GitHub Desktop.
Valida aberturas e fechamentos de colchetes em uma string
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
// adaptado de https://github.com/tryber/sd-05-live-lectures/blob/39.1/expressoes.py | |
const MATCHES = { | |
'}': '{', | |
']': '[', | |
')': '(', | |
'"': '"', | |
"'": "'", | |
"`": "`", | |
"```": "```" | |
}; | |
const ABERTURAS = Object.values(MATCHES); | |
const FECHAMENTOS = Object.keys(MATCHES); | |
var isValid = function (s) { | |
let aberturas = []; | |
for (let pos = 0; pos < s.length; pos++) { | |
const item = s[pos]; | |
if (ABERTURAS.includes(item)) { | |
aberturas.push(item); | |
} | |
if (FECHAMENTOS.includes(item)) { | |
try { | |
const ultimo = aberturas.pop(); | |
if (ultimo != MATCHES[item]) { | |
return 'invalid'; | |
} | |
} catch (error) { | |
return 'deu ruim'; | |
} | |
} | |
} | |
return 'valid'; | |
}; | |
const test = ['(){}[]', '()', '(]', '([)]', '{[]}']; | |
for (let pos = 0; pos < test.length; pos += 1) { | |
const item = test[pos]; | |
// console.log('item: ', item); | |
console.log('result: ', isValid(item)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment