Hone logo
Hone
Problems

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 value if it is already within the min and max range (inclusive).
  • Return min if the value is less than min.
  • Return max if the value is greater than max.

Key Requirements:

  • The function must be named clamp.
  • It should accept value, min, and max as 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 value is between min and max (inclusive), return value.
  • If value is below min, return min.
  • If value is above max, return max.

Edge Cases to Consider:

  • What happens if min is greater than max? The problem statement implies a valid range where min <= max. For this challenge, assume min <= 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, and max will 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.

Loading editor...
javascript