initials function

String? initials(
  1. dynamic from, {
  2. int max = 2,
})

Implementation

String? initials(from, {int max = 2}) {
  Iterable<String> _sanitize(source) {
    if (source == null) return [];
    if (source is Iterable) {
      return Lists.compact(source.expand((item) => _sanitize(item)));
    }

    return source
        .toString()
        .split(" ")
        .map((word) => word.replaceAll(notLetterOrNumber, ""));
  }

  final initials = _sanitize(from)
      .where((word) => word.isNotEmpty)
      .take(max)
      .map((word) => word[0].toUpperCase())
      .join("");
  if (initials.isEmpty) {
    return null;
  } else {
    return initials;
  }
}