Strategies for reducing cyclomatic complexity in JavaScript

I am facing an issue with a code snippet that sets height based on certain conditions and devices. The error message indicates that the Cyclomatic complexity is too high (28). How can I go about resolving this problem?

function adjustHeightForAttributes() {
        
    var elementHeight = document.getElementById('listSearchOptions');
    var childNoLen = $('.attributelistContainer .requestedAttr span').length;
    
    if (childNoLen >= 1) {
        $('.attributelistContainer').css({"overflow-y":"auto"}); 
    }
    
    // Media query checks
    var widthMinCheck = window.matchMedia("(min-width: 768px)").matches;
    var widthMaxCheck = window.matchMedia("(max-width: 1024px)").matches;
    var orientationCheck = window.matchMedia("(orientation: landscape)").matches;
    var orientationCheckPortrait = window.matchMedia("(orientation: portrait)").matches;
    // Boolean value checks
    var bothFalse = vm.searchByRoomNo === false && childNoLen === 0;
    var bothTrue = vm.searchByRoomNo === true && childNoLen >= 1;
    var roomSearchTrue = vm.searchByRoomNo === true && childNoLen === 0;
    var childLenTrue = vm.searchByRoomNo === false && childNoLen >= 1;
    // Scroll existence check
    var scrollExists = $('#listSearchOptions')[0].scrollHeight > $('#listSearchOptions')[0].clientHeight;
    
    if (widthMinCheck && widthMaxCheck && orientationCheck) {
        console.log("oreintationCheck.. " + orientationCheck);
        // Handling different scenarios based on conditions
        if (bothFalse) {
            // Code block based on condition
        }
        if (childLenTrue) {
            // Code block based on condition
        }
        if (bothTrue) {
            // Code block based on condition
        }
        if (roomSearchTrue) {
            // Code block based on condition
        }
    } else if (orientationCheckPortrait) {
        // Handle scenarios for portrait orientation
    } else {
        // Fallback scenario handling
    }
}

Answer №1

For more information on Cyclomatic complexity, you can visit the wiki page here.

Cyclomatic complexity is calculated based on the number of branch statements in a method, such as if, else, for, while, etc.

To improve your code, consider refactoring your method into multiple smaller methods with fewer if-else statements in each.

You seem to have numerous if-else statements and nested ifs in your code. It would be beneficial to refactor them for better readability and maintainability.

function bothTrue_scrollExists(bothTrue, scrollExists)
    if (bothTrue) {
        if (scrollExists) {
            console.log("Height..in adjustSearchAttributesheight12." + $('#listSearchOptions')[0].clientHeight);
            $('#listSearchOptions').css({"max-height":"18.5vh"});
        }
        else {
            console.log("Height..in adjustSearchAttributesheight13." + $('#listSearchOptions')[0].clientHeight);
            $('#listSearchOptions').css({"max-height":"20.8vh"});
        }
    }
}

EDIT: Consider optimizing your logic with the following implementation.

var s = '';

if (widthMinCheck && widthMaxCheck && orientationCheck) {
    s = s + 'A';
}
else if (orientationCheckPortrait) {
    s = s + 'B';
}
else{
    s = s + 'C';
}
//////////////////////////////////////////
if (bothFalse) {
    s=s+'_'+'BF';
}
else if (childLenTrue){
    s=s+'_'+'CT';
}
else if (roomSearchTrue){
    s=s+'_'+'RS';
}
else if (bothTrue){
    s=s+'_'+'BT';
}
//////////////////////////////////////////
if (scrollExists) {
    s=s+'_'+'SE';
}
else {
    s=s+'_'+'NS';
}
var data = {
     'A_BF_NS' : 52,
     'B_BF_SE' : 38//Add other combinations here
};
console.log("Height..in adjustSearchAttributesheight." + $('#listSearchOptions')[0].clientHeight);
var height = (data[s])? data[s] : 'auto';
$('#listSearchOptions').css({"max-height":height+"vh"});

Answer №2

According to information found on Wikipedia:

Cyclomatic complexity is a numerical measurement that indicates the quantity of distinct paths within a program's source code.

Each control statement (such as if/else or for loops) contributes to the overall cyclomatic complexity of a function.

Consider breaking down your function into smaller, more manageable functions to improve readability and maintainability.

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

Tips for managing the react-bootstrap carousel using personalized buttons

In order to have control over carousel slides using custom buttons, I managed to achieve this with reference to this Example. Below is the code implementation: import React, { useState } from "react"; import { Carousel, Button, Container, Row } ...

Using PHP to pass variables to an external JavaScript file

I have come across the following code snippet: PHP <?php include("db.php"); ?> <html> <head> <title>Title</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/j ...

Updating classes when useState changes in React JS

I'm currently working on implementing a carousel slider in React. As I track the state to determine the specific class to add based on the state value (e.g., adding "-left-1/3" when the state is 2), everything seems to be functioning correctly. Howeve ...

Struggling to integrate the navigation bar with Wordpress platform

For a while now, I have been facing challenges with the navigation bar on the WordPress theme I am currently creating. I am struggling to get the navigation bar to display correctly. Below is the code snippet from my header.php file: <body> &l ...

Looping through an array and appending distinct elements to a fresh array

I am currently facing an issue and seeking feedback on how to resolve it. Below is the JSON data: questions: [ { question: 'lala', answer: 'papa', categories: ['Handla'] }, { question: ...

Exploring the depths of Vue.js routing through nesting

My Current Route is function route(path, view) { return { path: path, meta: meta[path], component: resolve => import(`pages/${view}View.vue`).then(resolve) } } route('/', 'Home'), route('/help', 'Help ...

"Unlocking the secret to fetching the id of the clicked element within a Highchart context menu

Is it possible to retrieve the id of a clicked button on the highchart context menu? Alternatively, is there a way to execute the click function twice? const contextButtonArray = []; contextButtonArray.push({ { text: 'TEST BUTTON&ap ...

Basic node.js server that responds with HTML and CSS

I have successfully created a basic http server to send an HTML file as a response. However, I'm struggling with how to also send a CSS file so that the client can view the HTML page styled with CSS in their browser. Here is my current code: var htt ...

Chosen Buttons for Emailing

I have recently created a multistep form and have implemented functionality to receive the form contents via PHP email. However, I am facing a challenge where, when I navigate through the form and encounter multiple buttons to choose from, the email I rece ...

Issues with implementing Jquery datepicker in Django framework

I have thoroughly reviewed almost every question in this feed (at least I like to believe so). However, my jquery datepicker seems to be refusing to cooperate. Despite my best efforts, it has been quite some time since I've been trying to get it to wo ...

The post request in AngularJS is not successfully transmitting the data to the server

I have been encountering an issue where the model is null when I try to post data to the server. The data being sent is: {"email":"adas","password":"sds","grant_type":"password","client_id":"WebApp"} return $http.post(url, data,{headers: {'Content ...

Is it possible to use Vuejs v-model for a complete form instead of individual inputs?

Note: This solution is applicable for Vue 2.X I am currently working on a unique Vue.js component that has the ability to generate "custom" forms. This component essentially functions as a standalone form with multiple input fields. Users have the option ...

Ways to initiate the showModalDialog function within the C# script execution in ASP.NET 2.0, all without the use of Ajax

I have a scenario where I need to show a modal dialog in the middle of C# code execution and then continue the code based on a condition. Here is an example of what the code might look like: protected void Button_Click(object sender, EventArgs e) { //so ...

What is the best way to transfer a JSON response from VB to JS?

How can I transfer a JSON response from VB to JS? I'm currently working on updating a company website that processes payments through JSON request/response communication. The site is built in VB, and while I've been able to successfully send the ...

What is the best way to apply color to a line-through click event in React without affecting the font color?

I'm attempting to change the click event on a line-through element to turn red when clicked, but I can't find any solutions. I've tried various methods with no success. Edit: After adding "color":"red" following "none", the line is now red, ...

Manipulating Div Content with JQuery Based on Checkbox Selections

My goal is to extract content from a hidden div that contains an unordered list with specific classes and move certain list elements into placeholder divs based on checkbox values. Initially, when no checkboxes are checked, I want all list elements in the ...

When using nuxt-child, the parent component is not rendered

Here is how my folder structure is set up: |-profile |-- index.vue |-- address/index.vue After adding <nuxt-child />, I noticed that the content of profile/index.vue is not rendering properly. Instead, it seems to be loading a completely new route. ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

How to convert two arrays into JSON strings and store them in variables using JavaScript

After receiving an ajax response in JSON format, my JavaScript code (within the ajax response success function) stringifies two arrays. Now, I need to assign the data from one curly bracket to two variables, and the data from the other curly bracket to ano ...

Organizing HTML elements based on their class names, especially when an element has multiple classes assigned

Hey there, I've been working on an artist page that showcases multiple artists, each with a portfolio image and some detailed information. My goal is to have buttons at the top of the page that, upon clicking, will sort the artists displayed. To achi ...