Dart
Number helpers
Add number conversion and calculation methods.
The clamp method
We'll write a clamp method to keep a number in a given range. If the number is below the range it returns the lower bound, if above it returns the upper bound, otherwise it returns itself.
Example: clamp(15, 0, 10) gives 10 because 15 is greater than 10. clamp(-3, 0, 10) gives 0 because -3 is less than 0. clamp(5, 0, 10) gives 5. This helper fits user input, percentage calculation and graphic positioning.
Conditional return
The clamp method starts with two if statements; each checks one bound. If the condition holds, return gives back the relevant bound. Finally the value itself is returned.
Example: if (value < min) return min; if (value > max) return max; return value;. The first two conditions catch lower and upper bound violations; the last line covers the case where the value is within the range. This shape works cleanly without an extra else when the value is in range. return exits the method immediately, so later lines do not run.
Exercise Add clamp to Helper
Keep the existing Helper class. Add an int clamp(int value, int min, int max) method to the class. In the body write if (value < min) return min;, if (value > max) return max; and return value;. In main, create an instance with var h = Helper(); and call print(h.clamp(15, 0, 10)).
Show example solution
class Helper {
final String version;
Helper() : version = '1.0';
String slugify(String text) {
return text.toLowerCase().replaceAll(' ', '-');
}
int clamp(int value, int min, int max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
}
void main() {
var h = Helper();
print(h.clamp(15, 0, 10));
}
Test yourself
-
Complete the clamp signature
int clamp(int value, int min, ____) {
if (value < min) return min;
if (value > max) return max;
return value;
}
Show answer
int clamp(int value, int min, int max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
-
What does clamp(15, 0, 10) return?
Show answer
10 — Since 15 is greater than the upper bound 10, clamp returns 10.
-
Match the clamp parts
- clamp
- Method name
- min
- Lower bound
- max
- Upper bound
Next lesson: Date helpers