A clearer explanation of recursion and execution flow in JavaScript?

I read Eloquent JavaScript and I found this puzzle example:

Consider this riddle: starting from number 1 and adding 5 several times or multiplying by 3, an infinite number of new numbers can be produced. How would you write a function that, given a number, tries to find the sequence of additions and multiplications that produce a number?

Here is the code to solve:

function findSequence(goal) {
  function find(start, history) {
    if (start == goal)
      return history;
    else if (start > goal)
      return null;
    else
      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
}

print(findSequence(24));

Can someone clarify how dod find is executed if it had no value for the beginning and purpose of the arguments? Also, how did recursion happen?

+5
source share
3 answers

find start goal. 1 start, goal 24.

, . findSequence. . findSequence , , .

findSequence , find. , . findSequence , find(1, "1"). find . find goal; Javascript , goal findSequence, findSequence , goal , 24.

, . start goal, ; , . start , goal, null, , . start , goal, 5. , . 3 .

, , . 2, , findSequence null, 1 2, 5 3.

+5

find findSequence, , findSequence. :

function outerFunction() {
  var a = 2;
  function innerFunction() {
    alert(a);
  }
  innerFunction();
}
outerFunction();

, :

return find(1, "1");

1, 24 "1" .

: Rob Rob: , , find() findSequence(), .

+1

If I understand your question correctly: The last line of code calls findSequence () with a target of 24. In findSequence () there is a function called find () that is defined and then called in the opposite of findSequence, with an initial value of 1 and a history of 1.

0
source

All Articles