Reputation: 115
SonarQube identifies these 4 functions as duplicates in some specific lines:
Here is my 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 solution to fix the problem for the first two functions without having to merge them into a single one?
Thanks
Upvotes: 0
Views: 9742
Reputation: 1075427
You don't have to merge the functions, the problem is that you have exactly the same function in two places (the forEach
callback). Put that update of beneficiaries into its own function or method, and call that from both places:
// Outside the class
function updateBeneficiaires(beneficiaires, valueToAffecte) {
beneficiaires.forEach(beneficiaire => {
if (beneficiaire.percentage == "") {
valueToAffecte = Math.round(valueToAffecte * 100) / 100;
beneficiaire.percentage = "" + valueToAffecte;
}
});
}
// In the class
affectPercentageToBeneficiares(beneficiaires: BeneficiaryData[], sum: number) {
let numberOfBeneficiaresWithEmptyPrecentage = this.getBeneficiaresWithEmptyPercentageNumber(beneficiaires);
let valueToAffecte = (100.02 - sum) / numberOfBeneficiaresWithEmptyPrecentage;
updateBeneficiaires(beneficiaires, valueToAffecte);
}
affectPercentageToBeneficiaresInZeroCase(beneficiaires: BeneficiaryData[]) {
let numberOfBeneficiaresWithEmptyPrecentage = this.getBeneficiaresWithEmptyPercentageNumber(beneficiaires);
let valueToAffecte = (100) / numberOfBeneficiaresWithEmptyPrecentage;
updateBeneficiaires(beneficiaires, valueToAffecte);
}
(Or make it a class method, but it doesn't use any class state so perhaps a private static.)
Upvotes: 2