segmentBy method

List<List<T>> segmentBy(
  1. bool predicate(
    1. T,
    2. T
    )
)

When predicate(prev, next) is false, starts a new segment.

Implementation

List<List<T>> segmentBy(bool Function(T, T) predicate) {
  final List<T> list = toList();
  if (list.isEmpty) return <List<T>>[];
  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;
}