Return value from recurring function

后端 未结 2 821
一生所求
一生所求 2021-01-27 06:14

This Meteor server recursive method commonHint returns result undefined to the console even the finalRes has a value.
Any suggestion o

相关标签:
2条回答
  • 2021-01-27 06:46

    Any place you call commonHint you need to return the value of the call.

      ... 
    
      if (!hinters) {
        hinters = [...lib.getCombinations(['arg1', 'arg2', 'arg3'], 2, 3)];
        return this.commonHint(doc, shortMatches, hinters, results);  // hinters is an array of length 3 with 2 elements each
      }
    
      ...
    
      if (hinters.length > 0) {
        return this.commonHint(doc, shortMatches, hinters, results);
    
    0 讨论(0)
  • 2021-01-27 06:47

    Every path out of a recursive function that returns a result must return a result. In yours, you have paths that don't: When hinters isn't provided, and when hinters.length > 0 is true.

    You should return the result of the recursive call:

      if (!hinters) {
        hinters = [...lib.getCombinations(['arg1', 'arg2', 'arg3'], 2, 3)];
        return this.commonHint(doc, shortMatches, hinters, results);  // hinters is an array of length 3 with 2 elements each
    //  ^^^^^^
      }
    
      // ...
    
      if (hinters.length > 0) {
        return this.commonHint(doc, shortMatches, hinters, results);
    //  ^^^^^^
      } else {
        let finalRes = lib.mostCommon(results);
        console.log(finalRes);  //<==== has a value
        return finalRes;        //<==== so return it to caller
      }
    
    0 讨论(0)
提交回复
热议问题