sortIt<R extends Comparable> method

List<T> sortIt<R extends Comparable>([
  1. R selector(
    1. T
    )?
])

Returns a new list sorted by the value produced by selector.

Does NOT modify the original list.

Example:

final nums = [3, 1, 5, 2];
final sorted = nums.sortedBy((n) => n);
-> sorted = [1, 2, 3, 5]
-> nums remains = [3, 1, 5, 2]
  • If selector is provided → uses selector
  • If selector is null and T is Comparable → sorts by itself

Implementation

List<T> sortIt<R extends Comparable>([R Function(T)? selector]) {
  final copy = [...this];

  if (selector == null) {
    if (isEmpty || this.first is! Comparable) {
      throw StateError(
        "sortIt() without selector requires T to be Comparable.",
      );
    }
    copy.sort(); // direct sort for primitives
    return copy;
  }

  copy.sort((a, b) => selector(a).compareTo(selector(b)));
  return copy;
}