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

167
Visualizações
Can a JavaScript loop, upon the second iteration, iterate from the result of the prior iteration?

I just joined Stack Overflow and this is my first post so please do not hesitate to let me know if I am doing anything wrong.

I was presented with a challenge to create a function that accepts a string and calls another given function which swaps indices until the string is returned backwards.

I have gotten as far as below:

//given function
function swap(str, first, last){
    str = str.split('');
    let firstIndex = str[first];    
    str[first] = str[last];
    str[last] = firstIndex;
    str = str.join("").toString()
    return str;
}

//my function
let word = "Hello"
function reverseSwap(str) {
  let result = ""
  for (let i = 0; i < str.length/2; i++) {
  result += swap(str, i, str.length -1 - i);
  }
  return result;
}
console.log(reverseSwap(word))

This however returns "oellHHlleoHello", because each iteration swaps indices from the original string then concatenates. Is it possible, upon the second iteration, to have the loop iterate from the result of the prior iteration so the following occurs?:

result of first iteration: swap(word, 0, 4) which returns "oellH"
second iteration uses "oellH" instead of "Hello" to swap(1, 3) which returns "olleH"
Then, swap(2,2) which doesn't change anything.

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

0

It's not working because

  • Don't += add all new strings to your result. (This will append each swap string to your result.)
  • You have to manipulate always the "result" string. (You want to do a swap always on the updated version of the string. Not the original one)

Here is a simple solution:

function swap(str, first, last) {
  str = str.split("");
  let firstIndex = str[first];
  str[first] = str[last];
  str[last] = firstIndex;
  str = str.join("").toString();
  return str;
}

let word = "Hello";

function reverseSwap(str) {
  for (let i = 0; i < str.length / 2; i++) {
    str = swap(str, i, str.length - 1 - i);
  }
  return str;
}
console.log(reverseSwap(word));

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