clamp<A> function
- Bounded<
A> bounded
Returns a function that clamps a value of type A
within its bounds.
The function will return the bottom
if the value is less than the lower
bound and the top
if it is greater than the upper bound. If the value is
within the bounds, it will be returned as is.
Example:
void main() {
// Create a bounded type for integers in the range of 1 to 10
final boundedIntegers = Bounded<int>((x, y) => x.compareTo(y));
boundedIntegers.top = 10;
boundedIntegers.bottom = 1;
// Create the clamp function for integers
final clampInt = clamp(boundedIntegers);
// Use the clamp function to restrict a value within the bounds
int value1 = clampInt(5); // Output: 5 (Within the bounds)
int value2 = clampInt(15); // Output: 10 (Clamped to the upper bound)
int value3 = clampInt(-5); // Output: 1 (Clamped to the lower bound)
}
Implementation
A Function(A) clamp<A>(Bounded<A> bounded) {
return (A a) {
if (bounded.compare(a, bounded.bottom) < 0) {
return bounded.bottom;
} else if (bounded.compare(a, bounded.top) > 0) {
return bounded.top;
} else {
return a;
}
};
}