In Eloquent Javascript, the following example is given as a recursive function:
function findSolution(target) {
function find(start, history) {
if (start == target)
return history;
else if (start > target)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
console.log(findSolution(24));
A good explanation is given after, but I'm having trouble understanding why the
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
bit works. Why can you have an ||
without, it seems to me in any case, a boolean being worked on? How does find()
know to "come back" and to this part of the function and "try again" with start * 3
when it gets to a branch in which start > target
and thus is given a null
?