englishList function

String englishList(
  1. List<String> items,
  2. {String andString = ', and ',
  3. String sepString = ', ',
  4. String emptyString = 'nothing'}
)

Convert a list of items to a properly formatted english list.

Implementation

String englishList(List<String> items, {String andString = ', and ', String sepString = ', ', String emptyString = 'nothing'}) {
  if (items.isEmpty) {
    return emptyString;
  }
  if (items.length == 1) {
    return items[0];
  }
  String string = '';
  final int lastIndex = items.length - 1;
  final int penultimateIndex = lastIndex - 1;
  for (int i = 0; i < items.length; i++) {
    final String item = items[i];
    string += item;
    if (i == penultimateIndex) {
      string += andString;
    } else if (i != lastIndex) {
      string += sepString;
    }
  }
  return string;
}