Strategies for ensuring the successful execution of my recursive function

I am currently troubleshooting a recursive function, but I am struggling to identify the issue in my code.

The structure of my recursive function is as follows:

  public findParent(parentId: number, node: any): any {
    if (node !== undefined && node.id === parentId) {
      return node;
    } else {
      if (node.predicates && node.predicates.length > 0) {
        for (const element in node.predicates) {
          if (node.predicates[element].predicates !== undefined && node.predicates[element].predicates.length > 0) {
            return this.findParent(parentId, node.predicates[element]);
          } else {
            continue;
          }
        }
      }
    }
  }

The structure of the node object is as follows:

"node": [
      {
        "id": 0,
        "level": 0,
        "field": "",
        "op": "AND",
        "parentId": null,
        "predicates": [
          {
            "field": "",
            "predicates": [],
            "level": 1,
            "parentId": 0,
            "id": 1.1,
            "op": ""
          },
          {
            ...
          }
        ]
      }
    ]

My expectation is that when I provide a parent Id to the function, it should return the complete object along with its sub/child objects.

For example, if the parentId is set to 2.5,

              {
                "field": "",
                "predicates": [
                  {
                    "field": "",
                    "predicates": [],
                    "level": 3,
                    "parentId": 2.5,
                    "id": 3.7
                  },
                  ...
                ],
                ...
              },

should be returned.

However, at the moment, this function is not functioning as expected

Answer №1

The primary issue in the code lies in returning from recursion without verifying if the recursive call actually found a solution. To illustrate this concept further, consider https://i.sstatic.net/E2Bho.png Your algorithm progresses as follows: 0 -> 1.1 -> 1.2 -> 2.4. After iterating through the predicates of 2.4, it encounters nodes without any predicates, leading to a return back to 1.2. It's important to note that the same immediate return occurs at this step (

return this.findParent(parentId, node.predicates[element]);
), causing the algorithm to backtrack without considering any of 2.4's siblings. Essentially, the algorithm directly returns to the root once it reaches a node with only leaf children. I hope this explanation clarifies the situation.

Furthermore, why are you inspecting a node's children instead of simply recursing for the node itself? Is this intentional? Testing it with parentId = 1.1 also results in a return of undefined due to the absence of children in the node. Additionally, utilizing for ... of is preferred over for ... in when iterating through an array.

Cheers!

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

Guide on accessing js file in an Angular application

I have a component where I need to create a function that can search for a specific string value in the provided JavaScript file. How can I achieve this? The file path is '../../../assets/beacons.js' (relative to my component) and it's named ...

Developing a structure or definition for a Map

Currently, I have created a type and interface in TypeScript to explicitly define the things variable and the Map constructor call. type Things = Map<string, ThingValue>; interface ThingValue { label: string; count: number; } const things: Thi ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Unable to execute functions on observable outcomes

Let's discuss an interface called Vehicle, a class named Car that implements it, and a method within the class titled isColorRed: export interface Vehicle{ color : string; } export class Car implements Vehicle{ color : string; constructo ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

Displaying nested web service array data in Angular 4

I created a project that retrieves data from a web service API. However, the API contains nested arrays that also need to be displayed. How can I access the data from these nested JSON arrays? What is the correct way to extract this data within the HTML co ...

Steps to Turn Off Angular 2 Material Input Field

Please carefully review the Description below before proceeding: This is an HTML file containing code snippets: <div class="row col-md-2"> <mat-form-field appearance="outline" class="nameInput col-md-2"> <mat-label>One< ...

Attempting to simulate the behavior of Angular2 Token during testing

Currently, I am working on obtaining a token that is required for API authentication to retrieve a list. My approach begins with importing the angular2-token library: import { Angular2TokenService } from 'angular2-token'; After this, I include ...

Creating a Mocha+Chai test that anticipates an exception being thrown by setTimeout

Here is what I have: it('invalid use', () => { Matcher(1).case(1, () => {}); }); I am trying to ensure that the case method throws an exception after a delay. How can I specify this for Mocha/Chai so that the test passes only if an exce ...

Searching and updating elements within an array object in JavaScript - what's the best way to do this?

I am attempting to locate an element in the target array and update it in the source array. let sourceArray = [ { "userId": "123", "applicationId": "abc", "selections": [ { " ...

Utilizing Forms in a Post Request (including JavaScript fetch())

How do I include a form parameter in a POST request using JavaScript fetch()? For example: curl --form "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5b4c5b4e5a5840787a51454b585d">[email protected]</a>&quo ...

Leverage a single attribute from a Typescript interface within another interface

Let's imagine we have a TypeScript Interface like this export interface IMyObj { id: string; type: 'AA' | 'AZ' | 'XY'; ... } Now, I require another interface that includes the same type field export interfa ...

Encountering tsconfig.json issues following the integration of Tailwindcss v3 into Next.js (create-next-app --typescipt)

Upon opening my code in VS Code, I encountered the following error: Cannot find type definition file for 'accepts'. The file is in the program because: Entry point for implicit type library 'accepts' In an attempt to resolve this issue ...

Is it possible to apply a style change to several components at once using a single toggle switch

I am looking to implement a day/night feature on my web app, triggered by a simple toggle click. While I can easily add this feature to a single component using the navigation menu, I am faced with the challenge of incorporating it into multiple component ...

Error alert: The return type is missing in the array.map method

After running ESLint on my TypeScript code, I received a warning that says: "Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)". The warning specifically points to the lambda function within the map function. privat ...

Vue | The module does not have a default export statement

I encountered an issue with Vue3, TypeScript, and Vue CLI where I received the following error message: Module '"c:/Users/USER/Documents/top-secret-project/src/components/Features/Features.vue"' has no default export. This error occurre ...

Adjust the field type to supersede the type of the generic object

I'm looking to set the type of T (a generic) equal to the type of the listener field, so that I can have auto completion for "firstParameter" whether the listener is the default value or a custom one. Is this achievable? If not, is there another solut ...

The function `pickupStatus.emit` is not defined

Currently, I have a driver's provider that monitors changes in my firestore database and updates the status of a driver pickup request. Here is the function responsible for this process: getDriverPickupRequest(id) { this.DriverCollection.doc<Driv ...

Combining the Partial<CssStyleDeclaration> union type with a dictionary can lead to potential typing complications when the implicit any flag is

Using VueJS v-bind:style binding makes it possible to set CSS variables. I am attempting to create a union type that allows for the object passed to v-bind:style to retain typings for CssStyleDeclaration, while also being relaxed enough to accept an arbitr ...

Shattered raw emotion

Does anyone have any insight on how to resolve this error? I've hit a roadblock trying to figure out the issue in the message below. Here is the snippet of code: :label="` ${$t('cadastros.clientes.edit.status')}: ${cliente.status === ...