segmentBy method
When predicate(prev, next) is false, starts a new segment.
Audited: 2026-06-12 11:26 EDT
Implementation
List<List<T>> segmentBy(bool Function(T, T) predicate) {
final List<T> list = toList();
if (list.isEmpty) return <List<T>>[];
// Group consecutive runs: predicate(prev, curr) decides whether curr stays
// in the current run or begins a new one. The final run is flushed after the
// loop, since there is no boundary past the last element to trigger it.
final List<List<T>> out = <List<T>>[];
List<T> current = <T>[list[0]];
for (int i = 1; i < list.length; i++) {
if (predicate(list[i - 1], list[i])) {
current.add(list[i]);
} else {
out.add(current);
current = <T>[list[i]];
}
}
out.add(current);
return out;
}