Created
February 20, 2014 11:04
-
-
Save sz-alpar/31d83ed7a5cd5c62bc4b to your computer and use it in GitHub Desktop.
Constrict a value to an interval. If the value exceeds one of the boundaries, the result will hold the exceeded boundary.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var value = -50; | |
var max = 0; | |
var min = -30; | |
var result = value; | |
if (result >= max) { | |
result = max; | |
} else if (result < min) { | |
result = min; | |
} | |
console.log('result with ifs: ' + result); | |
// A much more elegant solution using Math.min and Math.max | |
result = value; | |
result = Math.min(max,Math.max(result,min)); | |
console.log('result with Math.max and Math.min: ' + result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment