ente/lib/extensions/list.dart

39 lines
1 KiB
Dart
Raw Normal View History

2022-11-12 06:33:09 +00:00
extension ListExtension<E> on List<E> {
List<List<E>> chunks(int chunkSize) {
final List<List<E>> result = <List<E>>[];
for (var i = 0; i < length; i += chunkSize) {
result.add(
sublist(i, i + chunkSize > length ? length : i + chunkSize),
);
}
return result;
}
// splitMatch, based on the matchFunction, split the input list in two
// lists. result.matched contains items which matched and result.unmatched
// contains remaining items.
2022-11-14 08:33:49 +00:00
ListMatch<E> splitMatch(bool Function(E e) matchFunction) {
final listMatch = ListMatch<E>();
for (final element in this) {
if (matchFunction(element)) {
listMatch.matched.add(element);
} else {
listMatch.unmatched.add(element);
}
}
return listMatch;
}
2023-06-07 12:02:53 +00:00
Iterable<E> interleave(E separator) sync* {
for (int i = 0; i < length; i++) {
yield this[i];
if (i < length) yield separator;
}
}
}
class ListMatch<T> {
List<T> matched = <T>[];
List<T> unmatched = <T>[];
2022-11-12 06:33:09 +00:00
}