batchByProperty<T, B> function

List<Tuple2<List<T>, B>> batchByProperty<T, B>(
  1. List<T> items,
  2. B propertyFunc(
    1. T
    )
)

Implementation

List<Tuple2<List<T>, B>> batchByProperty<T, B>(
    List<T> items, B Function(T) propertyFunc) {
  var batchPropPairs = <Tuple2<List<T>, B>>[];

  void addBatchPropPair(List<T> batch) {
    if (batch.isNotEmpty) {
      batchPropPairs.add(Tuple2(batch, propertyFunc(batch.first)));
    }
  }

  var currentBatch = <T>[];
  B? currentProp;

  for (var item in items) {
    var prop = propertyFunc(item);

    if (prop != currentProp) {
      addBatchPropPair(currentBatch);
      currentProp = prop;
      currentBatch = [item];
    } else {
      currentBatch.add(item);
    }
  }

  addBatchPropPair(currentBatch);

  return batchPropPairs;
}