Skip to content

[Feature Request] DateTime clamp  #52

@FMorschel

Description

@FMorschel

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;
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions