Top community members

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

[Edit]
EN

JavaScript - keeping number variable in range

12 points
Created by:
Kate_C
2739

Using JavaScript it is possible to keep variable in range in following ways

1. Min-Max functions example

// ONLINE-RUNNER:browser;

function keepRange(value, min, max) {
   var tmp = Math.min(value, max);

   return Math.max(tmp, min);
}

// Using:

//                      value  min   max
console.log( keepRange(     2,   1,  5) ); // 2
console.log( keepRange(     0,   1,  5) ); // 1
console.log( keepRange(     6,   1,  5) ); // 5
console.log( keepRange(     1,   1,  5) ); // 1
console.log( keepRange(     5,   1,  5) ); // 5
console.log( keepRange(    -2,   1,  5) ); // 1

2. Custom condition example

// ONLINE-RUNNER:browser;

function keepRange(value, min, max) {
   if (value < min) {
        return min;
   }

   if (value > max) {
        return max;
   }

   return value;
}

// Using:

//                      value  min   max
console.log( keepRange(     2,   1,  5) ); // 2
console.log( keepRange(     0,   1,  5) ); // 1
console.log( keepRange(     6,   1,  5) ); // 5
console.log( keepRange(     1,   1,  5) ); // 1
console.log( keepRange(     5,   1,  5) ); // 5
console.log( keepRange(    -2,   1,  5) ); // 1

 

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more