In search of the smartest, most efficient and readable way to do the below:
int one = 1, two = 2;
int larger = one < two?two:one;
I prefer(or a variadic version of the below):
int largest(one,two){return one<two?two:one;}
int larger = largest(one,two);
But dart has no inline or macro.
With List:
var nums = [51,4,6,8];
nums.sort();
in largest = nums.last
Or(Thank you, Günter Zöchbauer):
print([1,2,8,6].reduce(max));
Using math library:
import 'dart:math';
int largest = max(21,56);
Probably the best, but how efficient is max in comparison to the first approach?
Why the question?
With the first approach I must check comparisons are done right for each of them;hundreds of them sometimes. With the second, only one function to verify, but hundreds of function calls.
Let's say that x is the smaller number and y is the larger number. You know that if you multiply the smaller number by 4 and add 8 , you get the larger number. This means that you can write. 4⋅x+8=y. Moreover, you know that if you multiply the smaller number by 4 and add it to the larger number, the result will be 40 .
The answer is: max() !
I'm pretty sure just
import 'dart:math';
int largest = max(21,56);
is the best way. It is small enough to be inlined by a compiler (dart2js, VM) and it is the least surprise for the reader. For a custom implementation the reader had to investigate the function to be sure about what it does.
For collections of values I find this the most elegant way
from https://stackoverflow.com/a/20490970/217408
import 'dart:math';
main(){
print([1,2,8,6].reduce(max)); // 8
print([1,2,8,6].reduce(min)); // 1
}
Reordering a list just to get the min/max is quite inefficient
var nums = [51,4,6,8];
nums.sort();
in largest = nums.last
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