Created
May 31, 2018 23:37
-
-
Save gladchinda/1180ee925f60434cbb22eeab43e56540 to your computer and use it in GitHub Desktop.
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 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