2021-07-08 20:35:32 +02:00
|
|
|
import 'package:flutter/foundation.dart';
|
2021-04-26 12:54:57 +02:00
|
|
|
import 'package:tuple/tuple.dart';
|
|
|
|
|
2021-04-10 06:28:12 +02:00
|
|
|
extension IterableExtension<T> on Iterable<T> {
|
|
|
|
/// Return a new sorted list
|
2021-07-23 22:05:57 +02:00
|
|
|
List<T> sorted([int compare(T a, T b)?]) => this.toList()..sort(compare);
|
2021-04-10 06:28:12 +02:00
|
|
|
|
2021-07-08 20:35:32 +02:00
|
|
|
/// Return a new stable sorted list
|
2021-07-23 22:05:57 +02:00
|
|
|
List<T> stableSorted([int compare(T a, T b)?]) {
|
2021-07-08 20:35:32 +02:00
|
|
|
final tmp = this.toList();
|
|
|
|
mergeSort(tmp, compare: compare);
|
|
|
|
return tmp;
|
|
|
|
}
|
|
|
|
|
2021-04-10 06:28:12 +02:00
|
|
|
/// Return a string representation of this iterable by joining the result of
|
|
|
|
/// toString for each items
|
|
|
|
String toReadableString() => "[${join(', ')}]";
|
|
|
|
|
|
|
|
Iterable<U> mapWithIndex<U>(U fn(int index, T element)) sync* {
|
|
|
|
int i = 0;
|
|
|
|
for (final e in this) {
|
|
|
|
yield fn(i++, e);
|
|
|
|
}
|
|
|
|
}
|
2021-04-18 13:34:04 +02:00
|
|
|
|
2021-04-26 12:54:57 +02:00
|
|
|
Iterable<Tuple2<int, T>> withIndex() => mapWithIndex((i, e) => Tuple2(i, e));
|
|
|
|
|
2021-04-18 13:34:04 +02:00
|
|
|
/// Whether the collection contains an element equal to [element] using the
|
|
|
|
/// equality function [equalFn]
|
|
|
|
bool containsIf(T element, bool Function(T a, T b) equalFn) =>
|
|
|
|
any((e) => equalFn(e, element));
|
2021-06-26 16:28:21 +02:00
|
|
|
|
|
|
|
/// Same as [contains] but uses [identical] to compare the objects
|
|
|
|
bool containsIdentical(T element) =>
|
|
|
|
containsIf(element, (a, b) => identical(a, b));
|
2021-07-31 21:33:31 +02:00
|
|
|
|
|
|
|
Iterable<Tuple2<U, List<T>>> groupBy<U>({required U Function(T e) key}) {
|
|
|
|
final map = fold<Map<U, List<T>>>(
|
|
|
|
{},
|
|
|
|
(previousValue, element) =>
|
|
|
|
previousValue..putIfAbsent(key(element), () => []).add(element));
|
|
|
|
return map.entries.map((e) => Tuple2(e.key, e.value));
|
|
|
|
}
|
2021-08-07 22:34:44 +02:00
|
|
|
|
|
|
|
T? get firstOrNull {
|
|
|
|
try {
|
|
|
|
return first;
|
|
|
|
} on StateError catch (_) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
2021-04-10 06:28:12 +02:00
|
|
|
}
|