This is a recursive function to show on the screen the way to obtain X number through a mathematical calculation where only sumar 5 (+5)
or can be done multiplicar por 3 (*3)
, based on the number 1:
Example:
If I want to get to 13 from 1, I first multiply by 3, then add 5, then add 5 again.
findSolution(13) === (((1 * 3) + 5) + 5)
Javascript code:
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");
}
console.log(findSolution(13));
(((1 * 3) + 5) + 5)
Iterating only using +5:
6,1
11,1
16,1
null
Iterating multiplying by 3:
3,1
9,1
27,1
null
Therefore, I would like to know: How does the return find() || find()
? work, since I don't know how the function does it to decide between +5 or *3, or if it automatically generates two calls to FIND each time it makes a return, and in turn two calls by option?, something similar to the following tree:
The operator
||
in JavaScript evaluates the expression on the left and if it is not a falsy value (null in this case) it returns it, otherwise it returns the expression on the right.In this case this line:
It would be equivalent to:
Or to this:
But without creating any intermediate variables or executing the expression on the left twice
To complement @Carlos Muñoz's answer:
These would be the recursion calls: