Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

57
Views
++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.

7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs