splitByPredicate method

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

Splits the list into sublists based on a given predicate.

The predicate function takes two elements of the list as input and returns a boolean value. If the predicate returns true, a new sublist is created with the current element. If the predicate returns false, the current element is added to the last sublist.

Example usage:

var numbers = [1, 2, 3, 4, 5, 6];
var result = numbers.splitByPredicate((a, b) => a % 2 == b % 2);
print(result); // [[1], [2, 3], [4, 5], [6]]

Implementation

List<List<T>> splitByPredicate(bool Function(T, T) predicate) {
  var r = <List<T>>[];
  var l = toList();
  for (var i = 0; i < l.length; i++) {
    if (i == 0 || predicate(l[i - 1], l[i])) {
      r.add([l[i]]);
    } else {
      r.last.add(l[i]);
    }
  }
  return r;
}