Hone logo
Hone
Problems

Clamping a Number Within a Range in JavaScript

Clamping a number means restricting it to a specific range. This is a common operation in various applications, such as game development (limiting player movement), signal processing (preventing values from exceeding a certain threshold), and data validation. Your task is to write a JavaScript function that clamps a given number within a specified minimum and maximum value.

Problem Description

You need to create a function called clamp that takes three arguments: number, min, and max. The function should return the original number if it falls within the range [min, max] (inclusive). If the number is less than min, the function should return min. If the number is greater than max, the function should return max.

Key Requirements:

  • The function must handle both positive and negative numbers.
  • The function must correctly handle cases where min is greater than max. In such cases, the function should swap the values of min and max before clamping.
  • The function should return a number.

Expected Behavior:

The function should consistently return a value within the specified range, regardless of the input number.

Edge Cases to Consider:

  • min and max are equal.
  • number is equal to min.
  • number is equal to max.
  • min is negative and max is positive.
  • min is positive and max is negative.
  • number is a floating-point number.

Examples

Example 1:

Input: clamp(5, 1, 10)
Output: 5
Explanation: 5 is within the range [1, 10], so it is returned unchanged.

Example 2:

Input: clamp(-2, 0, 5)
Output: 0
Explanation: -2 is less than 0, so 0 is returned.

Example 3:

Input: clamp(12, 2, 8)
Output: 8
Explanation: 12 is greater than 8, so 8 is returned.

Example 4:

Input: clamp(3, 7, 2)
Output: 3
Explanation: min (7) is greater than max (2). The function swaps them, effectively clamping to [2, 7]. 3 is within this range, so 3 is returned.

Example 5:

Input: clamp(2.5, 1, 4)
Output: 2.5
Explanation: 2.5 is within the range [1, 4], so it is returned unchanged.

Constraints

  • number, min, and max will be numbers.
  • min and max can be positive, negative, or zero.
  • The function must execute in O(1) time complexity.
  • The function must not modify the original number, min, or max values.

Notes

Consider using a simple if-else statement or the ternary operator to implement the clamping logic. Think about how to handle the case where min and max are swapped efficiently. The goal is to write clean, readable, and efficient code.

Loading editor...
javascript