Skip to content

Instantly share code, notes, and snippets.

@kylefelipe
Last active July 6, 2022 23:01
Show Gist options
  • Save kylefelipe/63722f3c9eaef68db2d68bb44773f577 to your computer and use it in GitHub Desktop.
Save kylefelipe/63722f3c9eaef68db2d68bb44773f577 to your computer and use it in GitHub Desktop.
Valida aberturas e fechamentos de colchetes em uma string
// 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