sortIt<R extends Comparable> method
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
selectoris provided → uses selector - If
selectoris 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 || 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;
}