How can I craft a one-liner return line that also has conditionals? For example, if I want to make a 'return the median' one:
//assuming sorted input array
return ((inputArray.length % 2) && (inputArray[int(inputArray.length/2)] + inputArray[int(inputArray.length/2)+1]) / 2) || inputArray[int(inputArray.length/2)+1];
Is there anyway to make this work?
You should use the ternary operator:
return (inputArray.length % 2 != 0) ? (inputArray[int(inputArray.length/2)] + inputArray[int(inputArray.length/2)+1]) / 2 : inputArray[int(inputArray.length/2)+1];
Which is equivalent to:
if (inputArray.length % 2 != 0) {
return (inputArray[int(inputArray.length/2)] + inputArray[int(inputArray.length/2)+1]) / 2;
} else {
return inputArray[int(inputArray.length/2)+1];
}
If you want to use only &&
and ||
, you can use the following (which is not really a good programming style):
((inputArray.length % 2 != 0) || return inputArray[int(inputArray.length/2)+1]) && return (inputArray[int(inputArray.length/2)] + inputArray[int(inputArray.length/2)+1]);
Which is equivalent to:
(condition || return value2) && return value1;
So, thanks to the short-circuit evaluation of boolean operators:
condition
is true
, return value2
is not evaluated and return value1
will be executed.condition
is false
, return value2
will be evaluated.