splitWhere method

Iterable<Iterable<T>> splitWhere(
  1. bool test(
    1. T a,
    2. T b
    )
)

Groups Iterable together with elements that have a return value of true for test and returns a list of each group.

Iterabletestの返り値がtrueになる要素同士でまとめて1つのグループとし、各グループのリストを返します。

final array = [1, 1, 2, 2, 3, 4, 5, 6];
final splitted = array.splitWhere((a, b) => a == b); // [[1, 1], [2, 2], [3], [4], [5], [6]]

Implementation

Iterable<Iterable<T>> splitWhere(bool Function(T a, T b) test) {
  final res = <List<T>>[];
  for (final item in this) {
    if (res.isEmpty) {
      res.add([item]);
    } else {
      final found = res.firstWhereOrNull((e) {
        if (e.isEmpty) {
          return false;
        }
        return test.call(item, e.first);
      });
      if (found == null) {
        res.add([item]);
      } else {
        found.add(item);
      }
    }
  }
  return res;
}