How ${history} Records How The Program Reached The Final Solution?
This example from Eloquent JS explains how recursion works. I understand in general. BUT I couldn't get how ${history} records the path toward the final solution. I run it in htt
Solution 1:
In the example above you see function find(current, history)
being called from
return find(1, "1"); within function findSolution(target)
I have simplified that example it does the same thing
functionfind(current, history, target) {
if (current == target) {
return history;
} elseif (current > target) {
returnnull;
} else {
returnfind(current + 5, `(${history} + 5)`, target) || find(current * 3, `(${history} * 3)` , target );
}
}
console.log(find(1, "1", 88));
(${history} + 5)
is same as: '(' + history + 5 + ')'
since history is equal to "1" in the first call, history = "(1 + 5)" as a string.
current is equal to 1 current + 5 = 6, history = "(1 + 5)", target 88 now the function calls it self passing find(6, "(1 + 5)", 88)
next find calls it self again passing
find( 11, '(' + (1 + 5) + 5 + ')', 88 )
and the same process continue until if (current == target)
gets true
Post a Comment for "How ${history} Records How The Program Reached The Final Solution?"