Simplify the cognitive load of the function

I'm facing a challenge with a function that has a cognitive complexity of 24, however, we have a requirement to limit it to a maximum of 15.

export function parameterValueParser<T extends Structure>(
  structure: T
): (parameterValue: Value) => Parsed<T> | null {
  return (parameterValue: Value): Parsed<T> | null => {
    if (isParameterValueNumber(structure)) {
      return parseNumber(parameterValue) as Parsed<T> | null;
    }
    if (isParameterValueStruct(structure)) {
      const parameterValueChildren = parseStruct(parameterValue);
      if (parameterValueChildren == null) {
        return null;
      }
      const result = {} as { [_: string]: Parsed<Structure> };
      for (const key in structure) {
        if (structure.hasOwnProperty(key)) {
          const child = parameterValueChildren[key];
          if (child == null) {
            return null;
          }
          const parsedChild = parameterValueParser(structure[key])(child);
          if (parsedChild == null) {
            return null;
          }
          result[key] = parsedChild;
        }
      }
      return result as Parsed<T>;
    }
    return null;
  };
}

The cognitive complexity is mainly due to the nested if statements, especially those under a for..of loop. Even extracting the code into a separate function may not significantly reduce the complexity. Any suggestions on how to effectively reduce its complexity?

Answer №1

To enhance the code quality, it would be advisable to consider seeking feedback on codereview. A good starting point for refactoring would be:

1. Abstracting out literal types:

- export function parameterValueParser<T extends Structure>(structure: T): (parameterValue: Value) => Parsed<T> | null
+ type Parser<T> = (val: Value) => Parsed<T> | null;
+ export function parameterValueParser<T extends Structure>(structure: T): Parser<T>

2. Eliminating all type assertions:

- return parseNumber(parameterValue) as Parsed<T> | null;
+ return parseNumber(parameterValue);

3. Utilizing descriptive variable names (avoid excessively long or short names):

- const parameterValueChildren = parseStruct(parameterValue);
+ const children = parseStruct(val);

Following these steps, you can proceed with refining your logic by simplifying it "inside-out." Instead of checking the structure type in the parser, perform the check externally and return a dedicated parser for each type:

export function parameterValueParser<T extends Structure>(struct: T): Parser<T> {
    if (isParameterValueNumber(struct)) {
        return parseNumber;
    }
    if (isParameterValueStruct(struct)) {
        return structValueParser(struct);
    }
    etc....
}

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

Unable to view image when using material-ui CardMedia component

Hello, I've encountered a problem with rendering an image in my application. Let me explain the issue in a simplified manner. So, I have a card component (MyCardComponent) where I need to pass a string prop containing the image file location. The goa ...

Error: The function cannot be called because it is undefined

As a newcomer to JavaScript, I recently copied a script from jqueryui.com for the dialog widget and pasted it into my Yii project. However, upon testing the code, I encountered an error: Uncaught TypeError: undefined is not a function associated with the ...

Finding the location of PIE.htc in the Firebug tool

After encountering issues with CSS3 properties not working on IE 7 and IE 8, I decided to include PIE.HTC. Visit this link for more information Upon viewing the page in IE, I realized that the CSS3 properties were not being applied as expected. I attempt ...

Show only future events using JavaScript and XML

I am facing a challenge with an interactive map that showcases event dates in various regions of the United States. While the map successfully extracts data from an XML document and displays it, I am encountering an issue where events from 2014 are not bei ...

Adjust CRM 2011 settings to allow bulk editing exclusively for specific entities

Currently, my goal is to restrict bulk editing for most entities except for the "Campaign Response" entity. To accomplish this task, I have taken the following steps: Disabled the Out of the Box (OOTB) edit button globally (due to restrictions on editin ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...

Angular firebase Error: The parameter 'result' is missing a specified type and is implicitly assigned the 'any' type

I have encountered an issue with the code I am working on and both the result and error are throwing errors: ERROR in src/app/login/phone/phone.component.ts(48,75): error TS7006: Parameter 'result' implicitly has an 'any' type. s ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

modify the name attribute of a select dropdown using jQuery dynamically

In my current project, I am working on dynamically changing the "name" attribute for each select box based on user interactions. The scenario is as follows: When a user clicks on an option in the first select box, a new select box appears with the remainin ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...

Generate an interactive sitemap.xml in ReactJS for each request made to http://example.com/sitemap.xml

I am working on a single-page application (SPA) using reactjs, and I have links in the format of http://example.com/blog/:id. I want to dynamically generate a sitemap for this site. While I'm aware that there are npm packages like react-router-sitema ...

To subscribe to the display of [Object Object], you cannot use an *ngIf statement without being inside an *ngFor loop

In my angular Quiz project, I have a functionality where every user can create quizzes. I want to display all the quizzes that a logged-in user has completed. Here is how I attempted to achieve this: // Retrieving user ID and category ID inside Re ...

Determining the existence of a file on a different domain using JavaScript

One of the key tasks I need to achieve from JavaScript on my HTML page is checking for the existence of specific files: http://www.example.com/media/files/file1.mp3 // exists http://www.example.com/media/files/file2.mp3 // doesn't exist Keep in mi ...

Converting JavaScript QML objects to C++ QT components

I have a QML JavaScript function that generates and returns a component called Item: function createComponent() { var component = Qt.createComponent('MyComponent.qml'); var obj = component.createObject(container, {'x': 0, &apos ...

Tips for accessing .js variables in .ejs files

I am facing an issue with my index.js and list.ejs files in Express. Here is the relevant code: index.js: const express = require("express"); const app = express(); app.set("view engine", "ejs"); app.set("views", __dirname + "\\views"); let ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Exporting methods/functions in React Native

import { width as responsiveHeight } from "react-native-responsive-dimensions"; I am trying to export responsiveHeight with the name width. Can someone please guide me on the correct way to do this? The current approach is not yielding any results. ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

JavaScript code not functioning on WordPress website (no impact)

I've encountered a strange problem. Here is the code snippet: (function($){ $("#maps1").hover( function(){$("#kontakt_os_1").hide();} ); $("#maps2").hover( function(){$("#kontakt_os_2").hide();} ); $("#maps3").hover( ...