sortByString<T> static method

void sortByString<T>({
  1. required List<T> items,
  2. required String by(
    1. T a
    ),
  3. bool descending = false,
})

Sorts the given list by the length of the given parameter by. Default sorting order is ascending. This can be changed by setting the descending to true.

Implementation

static void sortByString<T>({
  required List<T> items,
  required String Function(T a) by,
  bool descending = false,
}) {
  for (int i = 0; i < items.length; i++) {
    for (int j = i; j < items.length; j++) {
      if (descending) {
        if (by(items[i]).length < by(items[j]).length) {
          T currentValue = items[j];
          items[j] = items[i];
          items[i] = currentValue;
        }
      } else {
        if (by(items[i]).length > by(items[j]).length) {
          T currentValue = items[j];
          items[j] = items[i];
          items[i] = currentValue;
        }
      }
    }
  }
}