humanize method

String humanize({
  1. bool precise = false,
})

Formats the duration as a human-readable string.

Implementation

String humanize({bool precise = false}) {
  if (isZero) return '0 seconds';

  final parts = <String>[];
  String formatUnit(int value, String singular) =>
      '$value ${value == 1 ? singular : '${singular}s'}';

  if (years > 0) {
    parts.add(formatUnit(years, 'year'));
  }
  if (months > 0) {
    parts.add(formatUnit(months, 'month'));
  }
  if (weeks > 0) {
    parts.add(formatUnit(weeks, 'week'));
  }
  if (days > 0) {
    parts.add(formatUnit(days, 'day'));
  }
  if (hours > 0) {
    parts.add(formatUnit(hours, 'hour'));
  }
  if (minutes > 0) {
    parts.add(formatUnit(minutes, 'minute'));
  }
  if (seconds > 0) {
    parts.add(formatUnit(seconds, 'second'));
  }

  if (precise) {
    if (milliseconds > 0) {
      parts.add(formatUnit(milliseconds, 'millisecond'));
    }
    if (microseconds > 0) {
      parts.add(formatUnit(microseconds, 'microsecond'));
    }
  } else if (parts.length > 2) {
    parts.removeRange(2, parts.length);
  }

  if (parts.isEmpty) {
    if (milliseconds > 0) {
      parts.add(formatUnit(milliseconds, 'millisecond'));
    } else if (microseconds > 0) {
      parts.add(formatUnit(microseconds, 'microsecond'));
    } else {
      parts.add('0 seconds');
    }
  }

  late final String text;
  if (parts.length == 1) {
    text = parts.first;
  } else if (parts.length == 2) {
    text = '${parts[0]} and ${parts[1]}';
  } else {
    final last = parts.removeLast();
    text = '${parts.join(', ')}, and $last';
  }

  return isNegative ? '-$text' : text;
}