Languages
[Edit]
EN

JavaScript - keeping number variable in range

12 points
Created by:
Kate_C
2952

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

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join