Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Created May 31, 2018 23:37
Show Gist options
  • Select an option

  • Save gladchinda/1180ee925f60434cbb22eeab43e56540 to your computer and use it in GitHub Desktop.

Select an option

Save gladchinda/1180ee925f60434cbb22eeab43e56540 to your computer and use it in GitHub Desktop.
var MIN_VALUE = 1;
var MAX_VALUE = 5;
/**
* boundedValue(val)
*
* Returns val if val between MIN_VALUE and MAX_VALUE both inclusive
*
* Otherwise, returns MIN_VALUE if val is less than MIN_VALUE
*
* Else, returns MAX_VALUE if val is greater than MAX_VALUE
*/
// METHOD 1: Using if/else statements
function boundedValue(val) {
if (val > MAX_VALUE) {
return MAX_VALUE;
} else if (val < MIN_VALUE) {
return MIN_VALUE;
} else {
return val;
}
}
// METHOD 2: Using ternary operation
function boundedValue(val) {
return (val > MAX_VALUE) ? MAX_VALUE : (val < MIN_VALUE) ? MIN_VALUE : val;
}
boundedValue(0); // 1
boundedValue(3); // 3
boundedValue(7); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment