I am having a hard time following this function. I do not understand how the variable start reverts back to 16 after it reaches a value of 26 which is greater than 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 at this for sometime, I have a few questions that might clarify a few things:
1) Is it a correct statement to say that each call to find keeps track of it's own start value? For example, when find(1) is called, it's has a start value of 1, when find(1 + 5) is called, find(1)'s start value is still one, but find(1 + 5) now has it's own start value of 6.
2) I am having a hard time following the stacktrace even if I see it printed out. This is how I am 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, it tries to call find(21 * 3) which also returns null.
This is the part I get stuck at, if both find(21 + 5) and find(21 * 3) return null, how does it know to call find(16 * 3) next. Why does it not do find(16 + 5) again?
Does it have something to do where find(21 + 5) and find(21 * 3) were called by find(16) and because those returned null into the calling function, it executed the second portion of the || statement which was find(16 * 3).

||returns the first item if it is true-ish, or the second item if the first item is false-ish (which includes null). It's a generalization of the boolean-or, and behaves similarly to a null-coalesce operator.var x = y || z; return x;.