Skip to content

Instantly share code, notes, and snippets.

@sz-alpar
Created February 20, 2014 11:04
Show Gist options
  • Save sz-alpar/31d83ed7a5cd5c62bc4b to your computer and use it in GitHub Desktop.
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.
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