Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

recursion - javascript closure tutorial from eloquent javascript

the question is pretty similar to this thread Javascript..totally lost in this tutorial.

    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));

I got stuck at this part :

    find(start * 3, "(" + history + " * 3)"); 

each time start goes beyond goal what does it do? it says it return null but when I test and put breakpoint on

    if (start == goal) it shoes this on the console

    history: "(((((1 + 5) + 5) + 5) + 5) + 5)"
    start: 26

    history: "(((((1 + 5) + 5) + 5) + 5) * 3)"
    start: 63

it add up *3 and take off +5, I don't understand how.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The return statement:

      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");

is an expression involving the "||" operator. That operator will cause the left-hand side to be evaluated. If the result of that is not null, zero, false, or the empty string, then that value will be returned. If it is one of those "falsy" values, then the second expression is evaluated and returned.

In other words, that could be re-written like this:

       var plusFive = find(start + 5, "(" + history + " + 5)");
       if (plusFive !== null)
         return plusFive;
       return find(start * 3, "(" + history + " * 3)")

If "start" ever exceeds "goal", the function returns null. Of course, if both the alternatives don't work, then the whole thing will return null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...