Mr. Learner
Mr. Learner

Reputation: 1038

Angular - How to minimise same code usage?

I'm not sure how to handle and change below implementation better.

I've two subscription method which re-assigns the value like below.

public patientLastStatus = "";

this.treatmentStageOne.subscribe(resp => {
      if (resp) {
        this.patientLastStatus = "Passed";
      }
    });
this.treatmentStageTwo.subscribe(resp => {
      if (resp) {
        this.patientLastStatus = "Still in Observation";
      }
    });

I understand , above are completely two different subscription. Here, the value of this.patientLastStatus is only re-assigned. but i don't understand on what basis Sonarqube shows me like Update or refactor this function so that its implementation doesn't duplicate the one on line 88.

How can changes that in better way?

Helps much appreciated

Thanks everyone.

Upvotes: 0

Views: 105

Answers (2)

ABGR
ABGR

Reputation: 5205

Sonarqube is throwing a warning because it sees a duplication.Try this.patientLastStatus updating through a method.

public patientLastStatus = "";

public updatePateintStatus = (status)=>{
   this.patientLastStatus = status;
}
this.treatmentStageOne.subscribe(resp => {
      if (resp) {
        this.updatePateintStatus("Passed");
      }
    });
this.treatmentStageTwo.subscribe(resp => {
      if (resp) {
        this.updatePateintStatus("Still in observations...");
      }
    });

Upvotes: 2

VLAZ
VLAZ

Reputation: 28958

You can extract this logic into a higher order function that takes in what the new assignment value would be:

const conditionalChange = newValue => 
  resp => {
    if (resp) {
      this.patientLastStatus = newValue;
    }
  }

Now you can just re-use it in both subscriptions without duplicating the code:

this.treatmentStageOne.subscribe(conditionalChange("Passed"));
this.treatmentStageTwo.subscribe(conditionalChange("Still in Observation"));

Upvotes: 4

Related Questions