Minimize the count of switch cases that are not empty

How can I optimize the number of cases in my switch statement to align with SonarQube recommendations? Currently, I have 37 cases in a switch statement, but SonarQube recommends only 30.

I believe that my code is functioning correctly, and the issue lies solely in how SonarQube interprets it as a CodeSmell. Below is the reducer code in question:

export function equipmentReducer(
  lastState: IEquipmentState = new EquipmentState(),
  action: GenericAction<EquipmentActionTypes, any>
): IEquipmentState {
    // switch cases here...
}

Answer №1

One way to minimize the code is by identifying common returns and setting up a map. For instance, if reducerUtils.requestListData is being called multiple times (in this case 5 times), you can simplify it by using a map to handle the differences and eliminate unnecessary switch cases.

My initial suggestion is to convert action.types that have shared return functions into a new map (myMap) with keys corresponding to the specific different parameters (for example, option1 and option2). If you're unsure about the rest of your code, another approach could be to replace option1 with unknown or a list of possibilities separated by | inside <>.

const myMap = {
    [EquipmentActionTypes.REQUEST_EQUIPMENT]: {
      option1: IEquipment[],
      option2: ['equipmentList']
    },
    [EquipmentActionTypes.REQUEST_INITIAL_SPECIFICATION]: {
      option1: IEquipmentInitialSpecification[],
      option2: ['equipmentInitialSpecification']
    },
    ...
}
switch (action.type) {

    case EquipmentActionTypes.REQUEST_INITIAL_SPECIFICATION:
    case EquipmentActionTypes.REQUEST_MANUFACTURERS:
    ...
      return reducerUtils.requestListData < IEquipmentState, myMap[action.type].option1 > (lastState, myMap[action.type].option2);

Building on the previous concept, you might be able to streamline the process further by moving the function into option1 and completely eliminating the switch case. For more insights, check out this related article or this one.

const myMap = {
    [EquipmentActionTypes.REQUEST_EQUIPMENT]:{
        option1: reducerUtils.requestListData<IEquipmentState, IEquipment[] >(),
        option2: ['equipmentList']
    },
    ...
}
myMap[action.type].option1(lastState, myMap[action.type].option2, actionPayload)

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

What is the process for reducing the value displayed on the label?

I have three labels and I would like to subtract the value of two labels and place the result in the third label. $(document).ready(function() { //Retrieve the values from both labels var value1 = document.getElementById("addition").innerText; ...

Angular: proper dependency injection may not occur when appending .js or .ts at the end of an import statement

When it comes to import statements, the format is usually as follows: import {HelpService} from '../../help.service' It's worth noting that if I utilize autowiring to inject HelpService into the constructor, an already existing instance of ...

What causes a hyperlink to take longer to load when using href instead of routerLink in Angular 2+?

As I work on my web application using angular 2 and incorporating routes, I noticed a significant difference in loading speed based on how I link to another component. Initially, being new to angular, I used the href attribute like this: <a href="local ...

What is the best way to set one property to be the same as another in Angular?

In my project, I have defined a class called MyClass which I later utilize in an Angular component. export class MyClass { prop: string; constructor(val){ this.prop = val; } public getLength(str: string): number { return str.length; } ...

The coloring feature in Excel Add-in's React component fails to populate cells after the "await" statement

Currently, I am developing a Microsoft Excel Add-in using React. My goal is to assign colors to specific cells based on the value in each cell, indicated by a color code (refer to the Board Color column in the image below). To achieve this, I retrieve the ...

Having trouble getting my Angular project up and running - facing issues with dependency tree resolution (ERESOLVE)

Currently, I am in the process of following an Angular tutorial and I wanted to run a project created by the instructor. To achieve this, I referred to the steps outlined in the 'how-to-use' file: How to use Begin by running "npm install" within ...

What is the best way to access the second item using getByRole in React Testing Library when there is no specific name?

I am familiar with using the name option to select the first item here, but how can I go about selecting the second item if it does not have a name identified? -------------------------------------------------- button: Enter "Go": ...

Can Angular's change detection be triggered by a change in @Input?

As of now, I am immersing myself in guides and tutorials on Angular's change detection. There are some statements that are quite perplexing to me. Therefore, I am seeking confirmation or clarification. The default Change Detection is activated "every ...

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

The error code TS2345 indicates that the argument type 'Event' cannot be assigned to a parameter type 'string'

Hello, I'm a newcomer to utilizing Angular and I'm struggling to identify where my mistake lies. Below is the TypeScript code in question: import { Component } from '@angular/core'; @Component({ selector: 'app-root' ...

Addressing Equity Concerns within JavaScript Programming

I can't figure out why the final line in this code snippet is returning false. Is it not identical to the line above? const Statuses = Object.freeze({ UNKNOWN : 0, OK : 1, ERROR : 2, STOPPED : 3 }); class myStatus extends Object{ co ...

What is the importance of using a server to host an Angular 2 app?

I recently finished developing a front-end application in Angular 2 using angular-cli. After completion, I created a bundle using the command ng build. Here's what puzzles me - my app consists only of JavaScript and HTML files. So why do I need to h ...

Using PHP and JavaScript to keep track of file modifications

Being a beginner in PHP and Javascript, I recently created a basic Clock application using Javascript which worked out successfully. Now, I have a file that will automatically change its content. For example, it might look something like this: "12h15: eat ...

Tips for quickly rendering over 10,000 items with React and Flux

What is the most efficient way to render a large number of items in React? Imagine creating a checkbox list with over 10,000 dynamically generated checkbox items. I have a store that holds all the items and serves as the state for the checkbox list. Whe ...

Advantages of using ConfigService instead of dotenv

What are the benefits and drawbacks of utilizing @NestJS/Config compared to using dotenv for retrieving environment variables? Although I can create a class to manage all envvars in both scenarios, is it necessary? I am aware that @NestJS/Config relies on ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...

The ng-show directive is failing to update properly after changes are made to the scope values

I'm experiencing some issues with the ng-show method. I have set it up like this: Even though the username string length is checked, the ng-show method doesn't seem to hide/show the extra text until after another keystroke. How can I make it upd ...

Why isn't the mounted() lifecycle hook being triggered in my Vue 3 component?

I am struggling with a simple Vue 3 component that closely resembles some examples in the documentation. Here is the code: // Typewriter.vue <template> <div id="wrapper"> <p>{{ text }}</p> </div> </templa ...

Creating a new attribute within a JavaScript object by utilizing the properties of its sibling elements

Imagine a scenario where you have a complex array of objects structured like this: [ { "title": "Fundamentals", "order": 1, "lessonRef": "fundamentals", "children": [ { "title": "History", "order": 1, "lesso ...

combine object with an array attribute

If we have the following objects: let firstObject = {items: ["apple"]}; let secondObject = {items: ["orange"]}; and then execute Object.assign(firstObject, secondObject); the new state will be: firstObject.items[0] //"orange" firstObject.items === sec ...