Explain this javascript function from Eloquent Javascript -
i having hard time following function. not understand how variable start
reverts 16 after reaches value of 26 greater 24.
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));
ok, after looking @ sometime, have few questions might clarify few things:
1) correct statement each call find keeps track of it's own start value? example, when find(1) called, it's has start value of 1, when find(1 + 5) called, find(1)'s start value still one, find(1 + 5) has it's own start value of 6.
2) having hard time following stacktrace if see printed out. how viewing it:
find(1) calls find(1 + 5) //start = 1
find(6) calls find(6 + 5) // start = 6, passes
find(11) calls find(11 + 5) // start = 11, passes
find(16) calls find(16 + 5) // start = 16, passes
find(21) calls find(21 + 5) // start = 21, fails
because find(21 + 5) returns null, tries call find(21 * 3) returns null.
this part stuck at, if both find(21 + 5) , find(21 * 3) return null, how know call find(16 * 3) next. why not find(16 + 5) again?
does have find(21 + 5) , find(21 * 3) called find(16) , because returned null calling function, executed second portion of || statement find(16 * 3).
it's different variable. start whenever particular find(x) called, value of start doesn't affect other instance of start.
when find(21) called, returns null, because find(26) , find(63) return null likewise, find(16) , find(11) return null
when find(6) called, calls find(11), returns null, calls find(24) next. in context of call, start == 6, continues start + 5 , start * 3.
find(6): start = 6, history = (1 + 5) find(6 + 5): start = 11, history = ((1 + 5) + 5) find(11 + 5): start = 16, history = (((1 + 5) + 5) + 5) ... continued etc... find(11 * 3): start = 33, history = (((1 + 5) + 5) * 3) <end> find(6 * 3): start = 24, history = ((1 + 5) * 3)
Comments
Post a Comment