duration method

Duration? duration(
  1. String key
)

a number with a unit: 500ms, 30s, 5m, 2h, 1d. A plain number is seconds: 300 is 5 minutes.

Implementation

Duration? duration(String key) {
  String? value = raw(key);
  if (value == null) return null;
  RegExpMatch? match = _durationPattern.firstMatch(value.toLowerCase());
  if (match == null) {
    return _invalid(key, 'a Duration (like 500ms, 30s, 5m, 2h, 1d)', value);
  }
  int amount = int.parse(match.group(1)!);
  return switch (match.group(2)) {
    'ms' => Duration(milliseconds: amount),
    'm' => Duration(minutes: amount),
    'h' => Duration(hours: amount),
    'd' => Duration(days: amount),
    _ => Duration(seconds: amount),
  };
}