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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With