Ok, I don't know how to put this in short.
This is my code:
var ratio, input={w:100,h:50};
if(input.w <= input.h) ratio = input.h / input.w;
else ratio = input.w / input.h;
Question:
Is there faster, better, "less code needed" way to calculate ratio
? Than if/else statements.
Thanks!
You can use the ternary conditional operator. Syntax:
condition ? (statement if true) : (statement if false);
In your case:
ratio = (input.w <= input.h) ? (input.h/input.w) : (input.w/input.h);
EDIT:
This isn't faster than your solution, just faster to write. I would advise against using:
var ratio = Math.Max(input.w, input.h) / Math.Min(input.w, input.h)
That will compare the numbers twice (once in Math.Max, once in Math.Min) and would be slower.
var ratio = Math.max(input.w, input.h) / Math.min(input.w, input.h)
another [maybe more efficient]:
var ratio = Math.max(input.w / input.h, 1 / input.w / input.h);
even more efficient than ternary :
var ratio = w / h ;
ratio = ratio > 1 && ratio || 1/ratio
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