0

I don't understand why return weights_data returns undefined, and console.log(weights_data) returns something.

const getWeightReattributeProportionally = (weights_data, weight, z = 0) => {

  weights_data.forEach( (r, i) => weights_data[i] = (r * weight) + r );

  if ( weights_data.reduce( (a, b) => a + b) >= 0.9999999999999999 ) {

    console.log(weights_data);

    return weights_data;

  } else {

    getWeightReattributeProportionally(weights_data, weight *= weight, z += 1);

  }

}

const data = [0.12, 0.22, 0.32, 0.18]

const aaaa = getWeightReattributeProportionally(data, 0.16)

console.log(aaaa)
1
  • the condition is never met. it always returns false. Commented Oct 27, 2020 at 22:34

2 Answers 2

1

You forgot that you need to return the result of the recursive function:

const func = (weights_data, weight, z = 0) => {
  weights_data.forEach((r, i) => weights_data[i] = (r * weight) + r)
  if (weights_data.reduce((a, b) => a + b) >= 0.9999999999999999) {
    console.log(weights_data)
    return weights_data
  } else {
    return func(weights_data, weight *= weight, z += 1) // NEW!
  }
}

const data = [0.12, 0.22, 0.32, 0.18]

const aaaa = func(data, 0.16)

console.log(aaaa)

Also, you have a bug in your code: z is never used anywhere in your function

Sign up to request clarification or add additional context in comments.

1 Comment

Please upvote and mark my answer as accepted if it helped you :)
0

Unless your recursive function uses side effects (e.g., manipulating global/shared state, writing to a file, etc.) to do its job, every invocation, including the outermost, must return its results to its caller.

If it doesn't, how can the caller know what the recursive call did?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.