🤔️ 一種可能比 if-else / switch 更好的方式

image.png

背景

這兩天作 Code Review 的時候, 發現不少 if-else / switch 語句,並非特別優雅。 在一些邏輯複雜的地方,看起來比較臃腫, 不是那麼好讀。app

舉個例子:ide

function getTranslation(rhyme) {
  const lowercasedRhyme = rhyme.toLowerCase();
  if ( lowercasedRhyme === "apples and pears") {
    return "Stairs";
  } else if (lowercasedRhyme === "hampstead heath") {
    return "Teeth";
  } else if (lowercasedRhyme === "loaf of bread") {
    return "Head";
  } else if (lowercasedRhyme === "pork pies") {
    return "Lies";
  } else if (lowercasedRhyme === "whistle and flute") {
    return "Suit";
  }
  return "Rhyme not found";
}

這樣作看起來十分臃腫, 並且作了太多 lowercasedRhyme === 'xxx'的判斷, 之後有一個新的分支, 都須要判斷一次。ui

若是換成 switch 語句:spa

function getTranslation(rhyme) {
  switch (rhyme.toLowerCase()) {
    case "apples and pears":
      return "Stairs";
    case "hampstead heath":
      return "Teeth";
    case "loaf of bread":
      return "Head";
    case "pork pies":
      return "Lies";
    case "whistle and flute":
      return "Suit";
    default:
      return "Rhyme not found";
  }
}

狀況有所改善, 可是依舊顯得臃腫,咱們只須要返回一個值。code

遇到具備更復雜的功能時,也很容易錯過 break聲明, 形成錯誤。ip

再換一種方式:ci

function getTranslationMap(rhyme) {
  const rhymes = {
    "apples and pears": "Stairs",
    "hampstead heath": "Teeth",
    "loaf of bread": "Head",
    "pork pies": "Lies",
    "whistle and flute": "Suit",
  };
  return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}

咱們直接使用 key-value 的形式去取用數據, 最後用 ?? 最爲兜底。rem

這裏的 ??, 就是所謂的空位合併運算符 :文檔

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

不熟悉的朋友, 能夠去看一下文檔: https://developer.mozilla.org...get

若是遇到了更復雜一點的邏輯, 在適合的場景也能夠用這種方式來作, 好比:

function calculate(num1, num2, action) {
  const actions = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b,
    divide: (a, b) => a / b,
  };

  return actions[action]?.(num1, num2) ?? "Calculation is not recognised";
}

有一點注意一下,這裏咱們同時用到了 ?.?? 操做符。

結論

今天討論的這個問題,其實比較主觀, 帶有必定的我的偏好。

代碼的可讀性可維護性, 應該是咱們都須要注意的。

今天的內容就這麼多, 但願對你們有所幫助 image.png

相關文章
相關標籤/搜索