Drill

ProblemsJavaScript › validation

Keep a value inside its range

easyvalidationJavaScript

A slider hands back whatever the user dragged it to, and the settings layer pins it into the range the setting allows.

clampToRange(amount: int, low: int, high: int) → int

Solve it in the editor →

Where you start

function clampToRange(amount, low, high) {
  
}

Worked examples

CallResult
clampToRange(5, 1, 10)5
clampToRange(0, 1, 10)1
clampToRange(99, 1, 10)10
clampToRange(5, 10, 1)5

Hint

Sort the bounds first and the rest is two comparisons.

Reference solution in JavaScript
function clampToRange(amount, low, high) {
  const lo = Math.min(low, high), hi = Math.max(low, high);
  return Math.min(hi, Math.max(lo, amount));
}

The same problem in another language

More validation problems in JavaScript