dart - What is the smartest way to find the larger / smaller of two numbers -
in search of smartest, efficient , readable way below:
int 1 = 1, 2 = 2; int larger = 1 < two?two:one;
i prefer(or variadic version of 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 best, how efficient max in comparison first approach?
why question?
first approach must check comparisons done right each of them;hundreds of them sometimes. second, 1 function verify, hundreds of function calls.
i'm pretty sure just
import 'dart:math'; int largest = max(21,56);
is best way. small enough inlined compiler (dart2js, vm) , least surprise reader. custom implementation reader had investigate function sure does.
for collections of values find 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 list min/max quite inefficient
var nums = [51,4,6,8]; nums.sort(); in largest = nums.last
Comments
Post a Comment