Implement Clamp

EasyUtility Functions5 min4 tests

Implement a clamp function that restricts a number to be within a given range.

Requirements

  • If the number is below the minimum, return the minimum
  • If the number is above the maximum, return the maximum
  • If the number is within range, return it unchanged

Example

clamp(15, 0, 10); // 10
clamp(-5, 0, 10); // 0
clamp(5, 0, 10);  // 5
Hints (3)
  1. Think about which built-in Math functions can help you enforce boundaries.
  2. Math.max(value, min) ensures the value is at least min.
  3. Math.min(result, max) ensures the value is at most max.

Topics

  • Utility Functions

Asked at

Google · Apple · Stripe

Join Us
blur