Skip to content Skip to sidebar Skip to footer

Need Help To Understand An Example Of Recursion

I was trying to understand an example written in JavaScript. Actually, I'm reading the book Eloquent JavaScript, but got stuck while reading a topic about recursion. Here is the st

Solution 1:

A recursive function calls itself until the branch meets a condition where it doesn't call itself.

In this case the chain stops when the current value equals or is higher than the initial target value.

But I think that it should return null when the current equals the target.

With some extra logging one can follow better what happens.

In the snippet below, it exits with null when it meets the target of 11.
And because the result is null, it multiplies by 3 to get the final solution.

function findSolution(target) {

  function find(current, step, action) {
    console.log('step: '+step, '\taction: '+action, '\tcurrent: '+current);
    step++;
    if (current == target) {
       console.log(current+'='+target+' so exit with null')
       return null;
    } else if (current > target) {
       return current;
    } else {
      return find(current + 5, step, '+ 5') || find(current * 3, step, '* 3');
    }
  }

  return find(1, 0, 'start');
}

console.log(findSolution(11));

Post a Comment for "Need Help To Understand An Example Of Recursion"