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:
Which is equivalent to:
If you want to use only
&&and||, you can use the following (which is not really a good programming style):Which is equivalent to:
So, thanks to the short-circuit evaluation of boolean operators:
conditionistrue,return value2is not evaluated andreturn value1will be executed.conditionisfalse,return value2will be evaluated.