Refactor if statement JavaScript

  • A+
Category:Languages

I was wondering on how I can refactor that? I'm repeating myself I feel this is not the best way to write it :

if (operator === "+") {     strength += 2;     up = 4 * strength;     if (up > 40) up = 40;     final.base += up; } else if (operator === "-") {     up = 4 * strength;     if (up > 40) up = 40;     final.base -= up;     strength -= 2; } 

I don't really see a way to properly refactor that since position is important. Is there a way to clean this function?

 


You could write it more compact, if you do not use up later by using Math.min.

if (operator === "+") {     strength += 2;     final.base += Math.min(40, 4 * strength); } else if (operator === "-") {     final.base -= Math.min(40, 4 * strength);     strength -= 2; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: