Rice_Crisp
Rice_Crisp

Reputation: 1261

Limiting numbers without if statements

I was curious if there is a way to limit a number with javascript without using if statements. Say I have a number that goes from 0 to 100, but I only want it to allow 30 to 70. So anything less than 30 became 30 and anything greater than 70 became 70. With if statements it would look like this:

var x = 0;
if (x > 70) {
   x = 70;
}
if (x < 30) {
   x = 30;
}

I'm looking more for a solution involving arithmetic.

Upvotes: 1

Views: 475

Answers (5)

RBarryYoung
RBarryYoung

Reputation: 56745

Of course you can do it with the conditional ternary operator (.. ? .. : ..), but I assume that you are asking about just doing it with math only, no conditionals. If so, then you can do it with an Absolute function:

var x30 = x - 30;
var x30 = (x30 + Math.abs(x30)) / 2  + 30;
var x70 = 70 - x;
var x70 = 70 - (x70 + Math.abs(x70)) / 2;

Upvotes: 1

strah
strah

Reputation: 6732

Try this:

x = Math.min(70, Math.max(30, x));

Upvotes: 7

lededje
lededje

Reputation: 1869

Short circuiting

var x = Math.floor(Math.random()*100)

x = x > 70 ? 70 : (x < 30 ? 30 : x);

Single line, no if statments.

Or you can use max/min

var x = Math.floor(Math.random()*100)

x = Math.min(70, Math.max(30, x));

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125518

You could use conditional (ternary) operators and chain them like so

var x = 0;
x = x > 70 ? 70 : x < 30 ? 30 : x;

Not sure how readable this is though :)

Altenratively, you could use Math.min() and Math.max()

var x = 0;
x = Math.max(30, Math.min(x, 70));

Upvotes: 0

adeneo
adeneo

Reputation: 318302

There's always ternary expressions ?

var x = 0;
    x = x > 70 ? 70 : x;
    x = x < 30 ? 30 : x;

You can even join them

var x = 0;
    x = x > 70 ? 70 : x < 30 ? 30 : x;

Upvotes: 2

Related Questions