Ways to resolve sonar problem "Ensure this function is updated or refactored to avoid duplicating the implementation on line xxx"

SonarQube has detected duplicate functions in specific lines:

  1. beneficiaires.forEach(beneficiaire => {
  2. () => {

Below are the identified functions:

affectPercentageToBeneficiares(beneficiaires: BeneficiaryData[], sum: number) {
    let numberOfBeneficiaresWithEmptyPrecentage = this.getBeneficiaresWithEmptyPercentageNumber(beneficiaires);
    let valueToAffecte = (100.02 - sum) / numberOfBeneficiaresWithEmptyPrecentage;
    beneficiaires.forEach(beneficiaire => {
        if (beneficiaire.percentage == "") {
            valueToAffecte = Math.round(valueToAffecte * 100) / 100;
            beneficiaire.percentage = "" + valueToAffecte;
        }
    })
}

affectPercentageToBeneficiaresInZeroCase(beneficiaires: BeneficiaryData[]) {
    let numberOfBeneficiaresWithEmptyPrecentage = this.getBeneficiaresWithEmptyPercentageNumber(beneficiaires);
    let valueToAffecte = (100) / numberOfBeneficiaresWithEmptyPrecentage;
    beneficiaires.forEach(beneficiaire => {
        if (beneficiaire.percentage == "") {
            valueToAffecte = Math.round(valueToAffecte * 100) / 100;
            beneficiaire.percentage = "" + valueToAffecte;
        }
    });
}

this.userProfilService.updateUser(this.UpdatedUser)
    .subscribe(
        () => {
            this.toastr.success('User has been updated successfully', null, {
                enableHtml: true,
            });
        },
        (err) => {
            this.toastr.error('erreur dans la modification utilisateur', null, {
                enableHtml: true,
            });
        }
    );

this.userProfilService.addUser(this.User)
    .subscribe(
        () => {
            this.toastr.success('User has been created', null, {
                enableHtml: true,
            });
        },
        (err) => {
            throw err;
        }
    );

Is there a way to resolve the issue with the duplicate functions without merging them?

Thank you

Answer №1

To avoid merging the functions, just ensure that you have only one instance of the function being used in both places (the forEach callback). Extract the beneficiary update logic into its own separate function or method and invoke it from both locations:

// Define a standalone function outside the class
function updateBeneficiaries(beneficiaries, valueToAffect) {
    beneficiaries.forEach(beneficiary => {
        if (beneficiary.percentage == "") {
            valueToAffect = Math.round(valueToAffect * 100) / 100;
            beneficiary.percentage = "" + valueToAffect;
        }
    });
}

// Inside the class methods
affectPercentageToBeneficiaries(beneficiaries: BeneficiaryData[], sum: number) {
    let numberOfBeneficiariesWithEmptyPercentage = this.getBeneficiariesWithEmptyPercentageNumber(beneficiaries);
    let valueToAffect = (100.02 - sum) / numberOfBeneficiariesWithEmptyPercentage;
    updateBeneficiaries(beneficiaries, valueToAffect);
}

affectPercentageToBeneficiariesInZeroCase(beneficiaries: BeneficiaryData[]) {
    let numberOfBeneficiariesWithEmptyPercentage = this.getBeneficiariesWithEmptyPercentageNumber(beneficiaries);
    let valueToAffect = 100 / numberOfBeneficiariesWithEmptyPercentage;
    updateBeneficiaries(beneficiaries, valueToAffect);
}

(Alternatively, you can turn it into a class method, but since it doesn't rely on any class properties, consider making it private static.)

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

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

Angular 4: Conditional CSS classes causing issues with transitions

After scouring through stackoverflow, I have yet to find a solution to my current issue. I am utilizing a conditional class on a div that is applied when a boolean variable becomes true. Below is the code snippet in question: <div [class.modalwindow-sh ...

Custom Type Guard Leads to Intersection Type Outcome

Recently, I've been experimenting with Typescript and decided to explore the creation of an innovative Either type that could distinguish between success and failure scenarios. Utilizing a user-defined type guard, I managed to precisely narrow down th ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...

Tips for deciding on the appropriate CSS for an Angular 6 navbar component

I am currently working on an angular 6 application where users are assigned different roles that require distinct styling. Role 1 uses Stylesheet 1, while Role 2 uses Stylesheet 2. The Navbar component is a crucial part of the overall layout structure of ...

What happens when two style() functions are passed into the query() function for Angular Animations?

As someone who is relatively new to angular animations, I have reviewed the angular.io animation documentation multiple times in order to grasp how everything functions. While I believe I have a decent understanding, there are certain scenarios that the do ...

Upon running the "npm install" command, the node_modules folder appears to be

I found an interesting angular project that has been published on GitHub at https://github.com/pluralsight-projects/Angular-AlbumStoreProductPage. So, I decided to fork it and create a clone on my local machine which runs on Windows 10. The instructions ...

What is the best way to obtain the variable value?

What is the best way to pass a variable to the component sibling1? <parentComponent> <sibling1 [data]="parentData"></sibling1> </parentComponent> ...

Leveraging both Angular Material UI and Tailwind CSS simultaneously

Recently, I've been incorporating Material UI with Angular. With the deprecation of flexlayout and the rise of Tailwind as a recommended alternative, I'm wondering if it's feasible to utilize both Material UI and Tailwind in tandem. How can ...

I encounter an error message stating "Cannot read property 'push' of undefined" when trying to add an item to a property within an interface

I have a model defined like this : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode[]; } export interface TrackMode { trackNumber: number; ...

What is the best way to transfer the $event parameter from a dynamically generated function that requires the $event argument during a typical mouse click operation?

On an angular HTML template, I have a click handler that passes the $event argument to the handler function. My goal is to call this function programmatically on ngOnInit to initialize the component with default data as if the button had been clicked: Bel ...

The TypeScript compiler is attempting to locate relative path modules in an incorrect directory

Utilizing npm link to reference a typescript library I'm working on in my testing project. As a result, the structure of my node_modules directory appears like this: node_modules/ | myLib/ | | dist/ | | | subModule/ | | | | index ...

Error encountered while downloading file from S3 on NextJs due to network issue

I have encountered a network error while trying to download a file from Amazon S3. Despite configuring my Amazon config file correctly and using the S3.getObjectURl() method for the download, it still fails. Below is the snippet of my code: const AWSDownlo ...

Validation of decimal numbers in JavaScript without the presence of any other characters

Looking to create a JavaScript regex to validate an 8-digit number that may include decimals. The current regex /^\d+$/ allows for any other characters such as ( , * $ etc. How can I modify this to only accept numbers and periods? For example, the nu ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

Choose a specific location on a vehicle illustration within a pop-up window. The image should be partitioned into 6 separate sections

I have a project for my client where they need to choose a car and then indicate where the damage is located on an image, which is divided into 6 sections. I'm struggling to figure out how to achieve this. I initially thought z-index would work, but ...

Encountering issues accessing / Error within MEAN stack application

I recently completed the Heroku tutorial, which you can find here. I followed all the steps but did not deploy to the Heroku server and instead worked on my localhost. However, when I tried to access my application using localhost port 8080, I encountered ...

Issue with accessing custom method in subclass in Typescript

Recently delving into TypeScript, I decided to subclass Error and add a new method called getCode() in my MyError class. export class MyError extends Error { public code: number; constructor(code: number, message?: string) { super(mes ...

Unlocking the Magic: A Step-by-Step Guide to Generating PDFs with

I'm currently engaged in developing an IONIC venture employing JavaScript and Angular. One of the tasks entails creating a comprehensive PDF report featuring text, images, and graphs. Instead of hand-crafting all the elements, I'm keen on adoptin ...

Allow only numerical values through an ion-input in Ionic 4, preventing the input of letters and special characters

I am currently developing an application in Ionic 4 that requires users to enter only integer numbers (0-9). I need to prevent any other characters such as alphabets, dots, or plus signs from being entered. However, the methods I have tried so far have not ...