Define a larger number and divide

Well, I don’t know how to summarize it.

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 a faster, better, "less necessary code" way to calculate the ratio ? Than if / else.

Thanks!

+4
source share
5 answers

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:

It is not faster than your decision, just faster to write. I would advise against using:

 var ratio = Math.Max(input.w, input.h) / Math.Min(input.w, input.h) 

This will compare numbers twice (once in Math.Max, once in Math.Min) and will be slower.

+10
source
 var ratio = Math.max(input.w, input.h) / Math.min(input.w, input.h) 

another [perhaps more efficient]:

 var ratio = Math.max(input.w / input.h, 1 / input.w / input.h); 

more effective than triple:

 var ratio = w / h ; ratio = ratio > 1 && ratio || 1/ratio 
+7
source

Less is not necessarily faster:

 var ratio, input = {w:100, h:50}; ratio = input.w <= input.h ? input.h / input.w : input.w / input.h; 
+2
source

What about

 ratio = Math.max(input.w, input.h) / Math.min(input.w, input.h) 
+2
source

You can use the ternary operator:

 var ratio = (input.w <= input.h ? (input.h / input.w) : (input.w / input.h)); 
+1
source

Source: https://habr.com/ru/post/1384328/


All Articles