groupByList<T> function
Group consecutive elements together if they meet criteria.
Implementation
List<List<T>> groupByList<T>(
bool Function(T a, T b) groupFunction, Iterable<T> it) {
List<T> l = List.from(it);
if (l.isEmpty) {
return [];
}
if (l.length == 1) {
return [l];
}
List<List<T>> groups = [];
List<T> currentGroup = [l.first];
for (int i = 1; i < l.length; i++) {
if (groupFunction(l[i - 1], l[i])) {
currentGroup.add(l[i]);
if (i == l.length - 1) {
groups.add(currentGroup);
}
} else {
groups.add(currentGroup);
currentGroup = [l[i]];
if (i == l.length - 1) {
groups.add(currentGroup);
}
continue;
}
}
return groups;
}