how return one of the function between OR operator? [duplicate]

风流意气都作罢 提交于 2021-01-29 14:38:09

问题


I can not understand when the 'find' function will true or false in the else block. Here is the 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(24));

回答1:


|| works by first evaluating find(current + 5, `(${history} + 5 )`) and if it is truthy that is the final result. If it is falsy it will evaluate find(current * 3, `(${history} * 3)`) and whatever is the result will be the end result which is then returned.

You can replace return expra || exprb with code without || using if and bindings:

// expra and exprb can be any valid expression
// same as return expra || exprb;
const tmp = expra;  
if (tmp) {
    return tmp;
}
return exprb;


来源:https://stackoverflow.com/questions/60299157/how-return-one-of-the-function-between-or-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!