Skip to content

Instantly share code, notes, and snippets.

@stephen-lazaro
Last active October 5, 2018 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephen-lazaro/8872182685c2461f1272108697c576a1 to your computer and use it in GitHub Desktop.
Save stephen-lazaro/8872182685c2461f1272108697c576a1 to your computer and use it in GitHub Desktop.
// Again, producing an aggregation
const makeAggregation = (operation, initial) => ({
  operation: operation,
  initialValue: initial
});
// Combine them via running them on the same inputs in sequence
// If JavaScript weren't a single threaded run time, we could even do this in parallel!
const combineAggregation = (aggregationA, aggregationB) => ({
  reduction: ([priorA, priorB], record) =>
  [
  aggregationA.operation(priorA, record),
  aggregationB.operation(priorB, record)
  ],
  initialValue: [aggregationA.initialValue, aggregationB.initialValue]
});
// Sum balances by aggregating through _summation_ and _starting at zero_
const sumBalances = makeAggregation(
  (sum, record) => sum + record.balance,
  0
);
// Count via just adding 1 every time we see another record
const count = makeAggregation(
  (sum, record) => sum + 1,
  0
);
// Both take the count and sum the balances
const countAndSumBalances =
  combineAggregation(sumBalances, count);
// Now actually run those aggregations!
const getSumOfBalancesAndCount = report =>
 report.reduce(
  countAndSumBalances.operation,
  countAndSumBalances.initialValue
  );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment