How does a return a || b of a function in recursion in JavaScript?

4

This is a recursive function to show on the screen how to obtain X number through a mathematical calculation where you can only sumar 5 (+5) or multiplicar por 3 (*3) , having as base the number 1:

Example:

If I want to get to 13 from 1, first multiply by 3, then add 5 and then again add 5.

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

Iterando multiplying by 3:

3,1
9,1
27,1
null

So I would like to know: How does the return find() || find() work ?, since I do not know how the function works to decide between +5 or * 3, or if it automatically generates two calls to FIND each time you make a return, and in turn two calls per option ?, something similar to the following tree:

    
asked by Victor Alvarado 11.08.2017 в 00:50
source

2 answers

3

The operator || in JavaScript evaluates the expression on the left and if this is not a value falsy (null in this case) it returns it, otherwise it returns the expression on the right.

In this case this line:

return find(current + 5, "(" + history + " + 5)") ||
         find(current * 3, "(" + history + " * 3)");

It would be equivalent to:

var left = find(current + 5, "(" + history + " + 5)");
return left ? left : find(current * 3, "(" + history + " * 3)");

Or to this:

var left = find(current + 5, "(" + history + " + 5)");
if (left) {
    return left;
} else {
    return find(current * 3, "(" + history + " * 3)");
}

But without creating any intermediate variable or executing the expression on the left twice

    
answered by 11.08.2017 / 00:58
source
2

To complete the answer of @Carlos Muñoz:

These would be called recursion:

find(1, "1")
  find(6, "(1 + 5)")
    find(11, "((1 + 5) + 5)")
      find(16, "(((1 + 5) + 5) + 5)")
        muy grande
      find(33, "(((1 + 5) + 5) * 3)")
        muy grande
    find(18, "((1 + 5) * 3)")
      muy grande
  find(3, "(1 * 3)")
    find(8, "((1 * 3) + 5)")
      find(13, "(((1 * 3) + 5) + 5)")
        Encontrado!
    
answered by 11.08.2017 в 01:43