Better way of getting cumulative sum/running totals from one list to another list in Dart

Viewed 207

Here is what I want to do, better than I already am.

Salesperson counting his sales. Enters his data everyday and gives us a list like so:

List<int> weekOneDaily = [3, 4, 2, 7, 13, 34, 22];

I want to create a running total list from this above list so that every day is added to the next as its own entry like so:

List<int> cumulativeDaily = [3, 7, 9, 16, 29, 63, 85];

I am currently doing this successfully like so:

List<int> dailySales = [2, 9, 4, 16, 13, 23, 18];
List<int> cumulativeSales =[];

/// Create cumulative list totals
void getCumulative(List<int> list) {
  cumulativeSales.add(list.first);
  for (var index in list) {
    (index == list.first)
        ? cumulativeSales.add(index)
        : cumulativeSales.add(cumulativeSales.last += index);
  }
  cumulativeSales.removeLast();
  print('CUMULATIVE: $cumulativeSales');
}

getCumulative(dailySales);

This is somewhat strange as it gives two of same last elements so i need to remove last & need to pre-render the first for it to work.

Anyone point me to a more simple, less verbose, less hack solution?

Please note I do not want to do it like this video

1 Answers

I would properly do something like this:

/// Create cumulative list totals
List<int> getCumulative(List<int> list) => list.fold(
    [], (sums, element) => sums..add(element + (sums.isEmpty ? 0 : sums.last)));

void main() {
  print(getCumulative([2, 9, 4, 16, 13, 23, 18])); // [2, 11, 15, 31, 44, 67, 85]
}

Or this which is kinda more readable:

/// Create cumulative list totals
List<int> getCumulative(List<int> list) {
  var sum = 0;
  return [for (final value in list) sum += value];
}

void main() {
  print(getCumulative([2, 9, 4, 16, 13, 23, 18])); // [2, 11, 15, 31, 44, 67, 85]
}
Related