enloz
enloz

Reputation: 5824

Determine bigger number and divide

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!

Upvotes: 4

Views: 889

Answers (5)

Bart Calixto
Bart Calixto

Reputation: 19705

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

Upvotes: 7

Luchian Grigore
Luchian Grigore

Reputation: 258618

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.

Upvotes: 10

Cyclonecode
Cyclonecode

Reputation: 30031

You could use the ternary operator:

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

Upvotes: 1

Alex K.
Alex K.

Reputation: 175796

How about

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

Upvotes: 2

Asken
Asken

Reputation: 8051

Smaller not necessarily faster:

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

Upvotes: 2

Related Questions