Keep a value inside its range
A slider hands back whatever the user dragged it to, and the settings layer pins it into the range the setting allows.
- Below the bottom becomes the bottom; above the top becomes the top.
- If the two bounds arrive the wrong way round, swap them rather than refusing.
clampToRange(amount: int, low: int, high: int) → int
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func clampToRange(amount int, low int, high int) int {
}
Worked examples
| Call | Result |
|---|---|
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 Go
func clampToRange(amount int, low int, high int) int {
lo, hi := low, high
if lo > hi {
lo, hi = hi, lo
}
if amount < lo {
return lo
}
if amount > hi {
return hi
}
return amount
}