The outcome yielded by a repeating function

This recursive function commonHint in the Meteor server is causing result to be undefined in the console, even though finalRes has a value.
Any ideas on how to properly return finalRes to the caller? Thanks!


  // Calling the recursive method
  let result = this.commonHint(myCollection.findOne({age: 44}), shortMatches);
        console.log('got most common hint: ' + result); // <=== undefined ====

  'commonHint': function (doc, shortMatches, hinters, results = []) {
      // For first call when only the first 2 args are defined,
      if (!hinters) {
        hinters = [...lib.getCombinations(['arg1', 'arg2', 'arg3'], 2, 3)];
        this.commonHint(doc, shortMatches, hinters, results);  // Hinters is an array of length 3 with 2 elements each
        return;
      }

      // Get an element from hinters, use its 2 hinters and remove that element from the hinters
      let hintersToUse = hinters.pop();
      let hinter1 = this.cleanMatchItem(hintersToUse[0]);
      let hinter2 = this.cleanMatchItem(hintersToUse[1]);
      let intersect = _.intersection(hinter1, hinter2);

      // Find the item in shortMatches that best matches with the intersection
      let tempCol = new Meteor.Collection();
      for (let i = 0; i < shortMatches.length; i++) { tempCol.insert({match: shortMatches[i]}); }
      results.push(mostSimilarString(tempCol.find({}), 'match', intersect.join(' ')));

      if (hinters.length > 0) {
        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
      }
    },

Answer №1

It is crucial that every exit point in a recursive function yielding a result must produce a result. Your code contains some paths that do not follow this rule: Specifically, when the variable hinters is absent or when the condition hinters.length > 0 evaluates to true.

To rectify this issue, you need to ensure that you return the result of the recursive call as demonstrated below:

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
  }

Answer №2

Whenever you refer to a place as commonHint, the value of that reference must be returned.

  ... 

  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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript splice method mistakenly eliminating the incorrect elements

I have an array of objects like the one below: [{"name":"Rain"},{"name":"Storm"},{"name":"Forest"}] These objects are indexed as follows: [0, 1, 2]. I'm attempting to delete an item at a specific position using this code: $scope.selectedSound ...

Issue with Vue/Nuxt 3: Unable to modify properties of null when setting 'textContent'

I am currently facing an issue with a function that is designed to switch words every few seconds. The functionality itself is working fine, but I keep encountering the following error intermittently in the VSC console: TypeError: Cannot set properties o ...

A guide to validating a v-edit-dialog within a v-datatable

As I navigate my way through vue.js and vuetify, I am faced with an issue regarding the validation of input within a v-edit-dialog located inside a v-datatable. Despite having functional validation in place, the save button remains enabled and accepts inva ...

Ways to fix: Encountering an Unexpected token < in JSON at position 0

Hey there! I've just started dipping my toes into the MEAN stack. I'm currently using Angular to connect to an api.js file, which in turn connects to my mongodb database. However, I've come across this error: ERROR SyntaxError: Unexpected t ...

Issue with ng-cloak not resolving flicker on button in Chromium; strangely, ng-cloak CSS doesn't apply as expected

Here is a snippet of my HTML code: <button type="button" class="btn btn-primary ng-cloak" ng-click="ctrl.add(ctrl.userProfile.username)" ng-hide="ctrl.userProfile.added">Add</button> The code above is a part of the larger HTML document shown ...

Showing a <div> element sandwiched between two elements from different hierarchies

Consider this snippet of HTML code: <div style="background-color: blue"> <div style="color: red"> some content some content some content some content </div> </div> <div id="highlight" style="top: 0px; width: 20 ...

Stop the Text Table from being highlighted

My webpage includes a dynamic table where users can select multiple rows. jQuery events and CSS are utilized to provide visual feedback when a row is selected. However, pressing the shift key sometimes causes text to become highlighted, which is not idea ...

Troubleshooting an expressjs server in parallel with electron

I have managed to successfully run an ExpressJS server alongside Electron by following the instructions provided in this post: Run Node.js server file automatically after launching Electron App However, I am facing an issue where there is no output from t ...

Having trouble properly displaying information from a JSON array with jQuery

Having a basic array of data in a JSON file is presenting a challenge for a beginner like me when it comes to extracting the data. Here is the array that I have access to: var clients = [ { "clientid": "456489", "client-name": "John Smith", "e ...

Ways to split text across lines within my list

I am currently developing a shopping list app and everything is running smoothly. However, I am encountering an issue with breaking a long string into the next line. Even though I tried using word-wrap, it doesn't seem to work as intended. For exampl ...

What is the purpose of including the return keyword in this function to ensure the promise functions properly?

Code: script1.js: function retrieveData(fetch) { fetch('some API').then(res => res.json()).then(data => { return { count: data.count, results: data.results } }) } module.exports = retrieveData; script2: const ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

jQuery loading and updating

I am faced with a scenario where I have both a 'test.html' and a 'test.php' files. The content of 'test.html' is as follows: <html> <head> <script type="text/javascript" src="/js/jquery-1.8.2.js">< ...

Leverage ajax/js to dynamically refresh a single select tag within a set of multiple

While working on a project, I encountered a challenge while using JavaScript to update a <select> tag within a page. The specific issue arises because the page is designed in a management style with multiple forms generated dynamically through PHP ba ...

Problem with roles assigned through reactions on Discord

I've been working on a discord bot reaction roles command and everything seems to be going smoothly, except for one issue that I'm facing. After booting up the bot and running the command to create the embed, everything works fine. However, when ...

Incorporate information into a JSON structure within SAPUI5

While diving into SAPUI5, I decided to challenge myself by creating a basic form. Unfortunately, my attempts are falling short as the new entry I'm trying to add to my JSON model isn't showing up in the file when I run my code. No error messages ...

Unable to retrieve input value from dynamically-generated field with JQuery

There seems to be an issue with receiving a value from a static field when using the keyup method based on the input field class (.inputclass). Once a field is added dynamically, it does not get the value. Below is a sample code. Any help would be appreci ...

The for loop is not pausing to wait for the callback to complete within the loop

My objective is to display multiple .stl files in various divs on a webpage and retrieve model information for each model (such as volume, area, xyz coordinates, etc.). To accomplish this, I am utilizing , which is built on three.js The HTML code snippet: ...

Creating, customizing, and assigning values to data attributes in Draft-js blocks: A complete guide

My current setup involves a DraftJS editor displayed like this: <Editor editorState={this.state.editorState} handleKeyCommand={this.handleKeyCommand} onChange={this.onChange} placeholder="Write a tweet..." ref="editor" spellCheck={true} /&g ...

Using <span> tags to wrap sentences within <p> tags while maintaining the rest of the HTML formatting

In order to achieve my goal, I have utilized the following code to extract content within tags and encapsulate each sentence in tags for easier interaction. $('p').each(function() { var sentences = $(this) .text() ...