splitByPercentage<T> function

List<List<T>> splitByPercentage<T>(
  1. List<T> list,
  2. List<Percentage> splitPercentages
)

Takes a list and splits it based by the percentage values contained inside splits. 1,2,4,5,6 - 40%,40%,20% = [1,2, 4,5, 6]

Implementation

List<List<T>> splitByPercentage<T>(List<T> list, List<Percentage> splitPercentages) {
  var result = [<T>[]];
  var splitIndexes = splitPercentages.map((x) => list.length * (x() / 100)).toList();
  var stopAtIIndex = splitIndexes[0];
  splitIndexes.removeAt(0);
  var currentGroup = 0;

  for (var i = 0; i < list.length; ++i) {
    if (i >= stopAtIIndex) {
      stopAtIIndex += splitIndexes[0];
      splitIndexes.removeAt(0);
      currentGroup++;
      result.add([]);
    }

    result[currentGroup].add(list[i]);
  }

  return result;
}