代码之家  ›  专栏  ›  技术社区  ›  James

如何在ESLint中使用扁平嵌套三元结构?

  •  -1
  • James  · 技术社区  · 7 年前

    我有这样的代码:

    let upgrade;
    if (device.firmwareV !== latestFirmware.version) {
        upgrade = "Firmware is up to date.";
    } else if (!firmUpTool) {
        upgrade = "Cannot upgrade the firmware through this connection.";
    } else if (latestFirmware.type !== device.type) {
        upgrade = "Cannot upgrade firmware of this device.";
    } else {
        upgrade = upgradeControl(firmUpTool);
    }
    

    但我更喜欢使用三元运算符(条件 ? 价值1 : let 具有 const (在我看来,它看起来更整洁,尽管我很欣赏人们的不同意见):

    const upgrade =
        device.firmwareV !== latestFirmware.version ?
            "Firmware is up to date."
        : !firmUpTool ?
            "Cannot upgrade the firmware through this connection."
        : latestFirmware.type !== device.type ?
            "Cannot upgrade firmware of this device."
        : upgradeControl(firmUpTool);
    

    但ESLint给出了5个错误,比如 Expected indentation of 12 spaces but found 8. . 如果我遵循建议,我必须缩进代码,即使我给了它一个缩进规则:

    indent: [2, 4, {flatTernaryExpressions: true}]
    

    我可以通过删除每个警告后面的新行来消除这些警告 但在我看来,这使得台词过长,可读性较差。

    有没有更好的方法来布局平面嵌套的三元结构,或者我应该在这里使用其他ESLint规则?

    1 回复  |  直到 7 年前
        1
  •  2
  •   James    7 年前

    你可以使用一个功能,检查零件,如果有情况,可以提前返回 true

    其优点是可读性和可维护性更好。

    else 该函数可能提前退出。

    function checkUpgrade() {
        if (device.firmwareV !== latestFirmware.version) {
            return "Firmware is up to date.";
        }
        if (!firmUpTool) {
            return "Cannot upgrade the firmware through this connection.";
        }
        if (latestFirmware.type !== device.type) {
            return "Cannot upgrade firmware of this device.";
        }
        return upgradeControl(firmUpTool);
    }
    
    const upgrade = checkUpgrade();