Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use flat nested ternaries with ESLint?

I have some code like this:

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

But I would prefer to use the ternary operator (condition ? value1 : value2) because it allows me to replace let with const (and in my opinion it looks tidier, though I appreciate that opinions vary):

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

But ESLint give 5 erros like Expected indentation of 12 spaces but found 8.. If I follow the recommendations I have to indent the code even though I have given it an indent rule:

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

I can get rid of the warnings by removing the newlines after each ? but that makes lines excessively long and not as readable in my opinion.

Is there a better way of laying out flat nested ternaries or is there some other ESLint rule I should be using here?

like image 787
James Avatar asked Oct 15 '25 20:10

James


1 Answers

You could use a fucntion which check the parts and return early if a condition is true.

The advantage is better readably and maintainability.

The missing else parts is covered by a possible earlier exit of the function.

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();
like image 171
Nina Scholz Avatar answered Oct 18 '25 08:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!