Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
open brackets must be closed in the correct order in javascript
s = ['[', ']', '{', '}', '(', ')'];
copied = s;
console.log(copied.length);
var output;
for (i = 0; i < s.length; i++) {
  console.log('calling function', i);

  different();
}

function different() {
  if (copied[0] == '(' && copied[1] == ')') {
    copied.splice(0, 2);
    output = 'valid';
    console.log('checking', copied);
  } else if (copied[0] == '{' && copied[1] == '}') {
    copied.splice(0, 2);
    output = 'valid';
  } else if (copied[0] == '[' && copied[1] == ']') {
    copied.splice(0, 2);
    output = 'valid';
    console.log('checking', copied);
  } else {
    output = 'invalid';
  }
}

console.log(copied);
console.log(copied.length);
console.log('result is ', output);

i am getting the following output

6

calling function 0

checking [ '{', '}', '(', ')' ]

calling function 1

[ '(', ')' ]

2

result is valid

The problem is for loop runs only twice but it is supposed to run 6 times.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Fixed a few issues with the code. The primary one being that the OP's different() function examines the same part of the array, no matter the state of the loop...

const s = ['[', ']', '{', '}', '(', ')', '[', '***']

for (i = 0; i < s.length - 1; i += 2) {
  let result = different(s[i], s[i + 1]);
  console.log(result)
}

function different(a, b) {
  let match =
    (a === '(' && b === ')') ||
    (a === '[' && b === ']') ||
    (a === '{' && b === '}')
  return `"${a}" and "${b}" ${match ? '' : 'do not'} match`
}

A more scalable approach would put represent the syntax in data, like this...

const s = ['[', ']', '{', '}', '(', ')', '[', '***']
const delimiters = {
  '[': ']',
  '(': ')',
  '{': '}',
}

for (i = 0; i < s.length - 1; i += 2) {
  let result = different(s[i], s[i + 1]);
  console.log(result)
}

function different(a, b) {
  let match = delimiters[a] === b;
  return `"${a}" and "${b}" ${match ? '' : 'do not'} match`
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda