joinOxford method

String joinOxford({
  1. String coordinator = 'and',
})

Converts each element to a String and concatenates the strings taking into account serial comma (also known as Oxford comma).

Iterates through elements of this iterable, converts each one to a String by calling Object.toString, and then concatenates the strings taking into account the punctuation.

Implementation

String joinOxford({String coordinator = 'and'}) {
  final StringBuffer buffer = StringBuffer();
  final iterator = this.iterator;
  if (!iterator.moveNext()) return '';
  buffer.write(iterator.current);
  bool wroteMoreThanTwo = false;
  bool hasNext = iterator.moveNext();
  while (hasNext) {
    final current = iterator.current;
    hasNext = iterator.moveNext();
    if (!hasNext) {
      buffer.write(wroteMoreThanTwo
          ? ', $coordinator $current'
          : ' $coordinator $current');
      break;
    } else {
      buffer.write(', $current');
    }
    wroteMoreThanTwo = true;
  }
  return buffer.toString();
}