Last active
October 22, 2023 07:20
-
-
Save Lootwig/fee6e89ec7ec050c4534427106eae8a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum Timespan { | |
year, | |
month, | |
week, | |
day, | |
hour, | |
minute, | |
moment; | |
String get plural => '${name}s'; | |
String get singleItem => '1 $name'; | |
String nItems(int n) => | |
this == moment ? 'just a moment' : (n == 1 ? singleItem : '$n $plural'); | |
} | |
typedef TimeAmount = ({Timespan span, int count}); | |
extension on Duration { | |
int get inYears => (inDays / 365).floor(); | |
int get inMonths => (inDays / 30).floor(); | |
int get inWeeks => (inDays / 7).floor(); | |
int convert(Timespan t) { | |
return switch (t) { | |
Timespan.year => inYears, | |
Timespan.month => inMonths, | |
Timespan.week => inWeeks, | |
Timespan.day => inDays, | |
Timespan.hour => inHours, | |
Timespan.minute => inMinutes, | |
Timespan.moment => 1, | |
}; | |
} | |
String toCourseWordsString() { | |
assert(!isNegative, "Doesn't work with negative durations"); | |
final pair = Timespan.values | |
.map<TimeAmount>((span) => (span: span, count: convert(span))) | |
.firstWhere((pair) => pair.count > 0); | |
return pair.span.nItems(pair.count); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment