clamp method
Returns this Duration clamped to be in the range min
-max
.
The comparison is done using compareTo.
The arguments min
and max
must form a valid range where
min.compareTo(max) <= 0
.
Example:
var result = Duration(days: 10, hours: 12).clamp(
min: Duration(days: 5),
max: Duration(days: 10),
); // Duration(days: 10)
result = Duration(hours: 18).clamp(
min: Duration(days: 5),
max: Duration(days: 10),
); // Duration(days: 5)
result = Duration(days: 0).clamp(
min: Duration(days: -5),
max: Duration(days: 5),
); // Duration(days: 0)
Implementation
Duration clamp({Duration? min, Duration? max}) {
assert(
((min != null) && (max != null)) ? min.compareTo(max) <= 0 : true,
'Duration min has to be shorter than max\n(min: $min - max: $max)',
);
if ((min != null) && compareTo(min).isNegative) {
return min;
} else if ((max != null) && max.compareTo(this).isNegative) {
return max;
}
return this;
}