toDuration method

Duration toDuration()

Parses "SS", "MM:SS", or "HH:MM:SS" into a Duration.

Implementation

Duration toDuration() {
  final parts = split(':');

  int parse(String s, String label, {int max = 59}) {
    final v = int.tryParse(s.trim());
    if (v == null) throw FormatException('Invalid $label: "$this"');
    if (v < 0 || v > max) {
      throw FormatException('$label out of range: "$this"');
    }
    return v;
  }

  return switch (parts.length) {
    1 => Duration(seconds: parse(parts[0], 'seconds')),
    2 => Duration(
      minutes: parse(parts[0], 'minutes'),
      seconds: parse(parts[1], 'seconds'),
    ),
    3 => Duration(
      hours: parse(parts[0], 'hours', max: 23),
      minutes: parse(parts[1], 'minutes'),
      seconds: parse(parts[2], 'seconds'),
    ),
    _ => throw FormatException('Invalid duration format: "$this"'),
  };
}