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

139
Visualizações
++Argument returns different results than argument + 1 when calling a recursive function

Code challenge I was trying to solve:

Write a function that takes in a “special” array and returns its product sum; A “special” array is a non-empty array that contains either integers or other “special” arrays. The product sum of a “special” array is the sum of its elements, where “special” arrays inside it are summed themselves and then multiplied by their level of depth.

The depth of a “special” array is how far nested it is. For instance, the depth of [] is 1; the depth of the inner array in [[]] is 2; the depth of the innermost array in [[[]]] is 3.

I tried solving it like this:

const productSum1 = (array, multiplier=1) => {
    let result = 0;
    for ( const element of array) {
        if ( Array.isArray(element)) {
            result += productSum1(element, ++multiplier)
        } else {
            result += element;
        }
    }
    return result* multiplier;
}

My question is about multiplier++. The value of multiplier would persist after executing the top call on the stack rather than return to its previous value on the previous call. I had to decrement (--multiplier) multiplier in order for it to return the correct value. However, when I used used multiplier + 1, it would return to its previous value after the top call was executed. Why does this happen?

Apologies for my poorly written question. I am very new to programming and I'm sure this could be asked in a much better way.

about 4 years ago · Juan Pablo Isaza
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