问题
So there is this recursion example in chap 3 of Eloquent JavaScript, it goes like this: Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite set of numbers can be produced. How would you write a function that, given a number, tries to find a sequence of such additions and multiplications that produces that number?
And the given code is..
function findSolution(target) {
function find(current, history) {
if (current == target) {
return history;
} else if (current > target) {
return null;
} else {
return find(current + 5, `(${history} + 5)`) ||
find(current * 3, `(${history} * 3)`);
}
}
return find(1, "1");
}
Now there are couple of things which I don't understand. Like very first time we call the function what is it going to return? is it going to return (1, "1") and just ignore the inner function find?
and what is current and history in the example? I don't remember assigning their values?
回答1:
The first time you call findSolution()
it will return the result of the last line of that function find(1, "1")
. In that case "1" is history, which is being set by calling find
. The value of current
is 1, which was the first parameter in find(1, "1")
The important thing to understand is that you are calling a function that is calling a newly defined function find
. The results of that function, which will recursively call itself is an exercise left to the reader (you). Whatever that result is will be returned by findSolution
.
来源:https://stackoverflow.com/questions/65536432/cant-wrap-my-head-around-this-this-recursion-example