更好的方式来执行If语句?

时间:2020-05-18 13:25:12

标签: javascript if-statement refactoring

非常简单:我写了以下if/else语句:

   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);
    }
    }
   }

我知道可能有更好的方法,因为else{ }中的代码与if{ }基本上相同,但变量名有所更改,因此,对更改或重构有何建议?我想提高可读性和速度,同时完成与当前执行的任务相同的任务。

1 个答案:

答案 0 :(得分:1)

实际上,您可以简化此操作,一般方法是

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

对于使用Creature 1/2的记录语句,您还需要传递该信息,因此它可能类似于

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});

当然,如果您重构它以使用上面的attack函数,再次写出if / else可能会变短。