Clamp a Number Within a Range
You're tasked with creating a function that ensures a given number stays within a specified minimum and maximum boundary. This is a common operation in programming for tasks like graphics, game development, or data validation, where you need to prevent values from exceeding certain limits.
Problem Description
Create a Javascript function named clamp that takes three arguments: value, min, and max.
Your function should:
- Return the
valueif it is already within theminandmaxrange (inclusive). - Return
minif thevalueis less thanmin. - Return
maxif thevalueis greater thanmax.
Key Requirements:
- The function must be named
clamp. - It should accept
value,min, andmaxas arguments. - The function should be pure, meaning it doesn't have side effects and always returns the same output for the same input.
Expected Behavior:
- If
valueis betweenminandmax(inclusive), returnvalue. - If
valueis belowmin, returnmin. - If
valueis abovemax, returnmax.
Edge Cases to Consider:
- What happens if
minis greater thanmax? The problem statement implies a valid range wheremin <= max. For this challenge, assumemin <= max. - What if the inputs are not numbers? For this challenge, assume all inputs will be valid numbers.
Examples
Example 1:
Input: clamp(5, 0, 10)
Output: 5
Explanation: The value 5 is already within the range of 0 to 10, so it is returned as is.
Example 2:
Input: clamp(-2, 0, 10)
Output: 0
Explanation: The value -2 is less than the minimum of 0, so the minimum value 0 is returned.
Example 3:
Input: clamp(15, 0, 10)
Output: 10
Explanation: The value 15 is greater than the maximum of 10, so the maximum value 10 is returned.
Example 4:
Input: clamp(0, 0, 10)
Output: 0
Explanation: The value 0 is equal to the minimum boundary, so it is returned.
Example 5:
Input: clamp(10, 0, 10)
Output: 10
Explanation: The value 10 is equal to the maximum boundary, so it is returned.
Constraints
value,min, andmaxwill be integers or floating-point numbers.- It is guaranteed that
min <= max. - The function should be efficient, with a time complexity of O(1).
Notes
Think about how you can use conditional logic to check the value against both min and max. You might find that you can achieve the desired result with a few simple comparisons. Consider if there are any built-in Javascript Math methods that could simplify this task.