-
Notifications
You must be signed in to change notification settings - Fork 29
Closed
Description
Proposal
DateTime (maybe Duration as well?) clamp. Any suggestions are welcome. I just encountered a need for a DateTime clamp, perhaps this nullable option is not the best fit, but for my case it was.
Inspiration
num clamp(num lowerLimit, num upperLimit);
Actual implementation
extension ClampDateTime on DateTime {
DateTime clamp({DateTime? min, DateTime? max}) {
assert(
((min != null) && (max != null)) ? min.compareTo(max).isNegative : true,
'DateTime min has to be before max\n(min: $min - max: $max)',
);
if ((min != null) && compareTo(min).isNegative) {
return min;
} else if ((max != null) && max.compareTo(this).isNegative) {
return max;
} else {
return this;
}
}
}
extension DurationClamp on Duration{
Duration clamp({Duration? min, Duration? max}) {
assert(
((min != null) && (max != null)) ? min.compareTo(max).isNegative : 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;
} else {
return this;
}
}
}
jogboms
Metadata
Metadata
Assignees
Labels
No labels