TheDeveloperNextDoor
TheDeveloperNextDoor

Reputation: 195

Better way to do this If statement?

Pretty simple: I wrothe the following if/else statement:

   if (cr1.ins <= cr2.ins) {
     console.log("[ROUND 1] Creature 1 (#" + cr1.num + ") is attacking first.");
    cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
    console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
    if (cr2.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
      remove(cr2);
    } else {
      console.log("[ROUND 2] Creature 2 (#" + cr2.num + ") is attacking second.");
      cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
      console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
      if (cr1.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
      remove(cr1);
    }
    }
   } else {
    cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
    console.log("[ROUND 1] Creature 2 (#" + cr2.num + ") is going first.");
    console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
    if (cr1.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
      remove(cr1);
    } else {
      console.log("[ROUND 2] Creature 1 (#" + cr1.num + ") is going second.");
      cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
      console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
      if (cr2.hlt <= 0) {
      console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
      remove(cr2);
    }
    }
   }

I know there's probably a better way to do this, as the code in else{ } is basically the same as if{ } with some variable name changes, so, any suggestions for changes or refactoring? I'd like to improve readability and speed while accomplishing the same task as it performs currently.

Upvotes: 0

Views: 28

Answers (1)

Bergi
Bergi

Reputation: 664356

Indeed you can simplify this, the general approach would be

if (cr1.ins > cr2.ins) {
  [cr2, cr1] = [cr1, cr2]; // just swap them!
}
attack(cr1, cr2);
if (cr2.hlt > 0) {
  attack(cr2, cr1);
}

For your logging statements with Creature 1/2 you would also need to pass through that information, so it might become something like

const a = {designator: "Creature 1", creature: cr1},
      b = {designator: "Creature 2", creature: cr2};
const [first, second] = cr1.ins <= cr2.ins ? [a, b] : [b, a];
attack({attacker: first, defender: second, round: 1});
if (second.creature.hlt > 0)
  attack({attacker: second, defender: first, round: 2});

Of course, if you refactor this to use an attack function as above, it might become shorter to write out the if/else again.

Upvotes: 1

Related Questions