CodingNic

Categories and Summary

Define Average Monthly Spend Correctly

Categories and Summary 16 min read

Define Average Monthly Spend Correctly

Open:

text
client/src/pages/SummaryPage.jsx
client/src/lib/monthlyTotals.js

An average needs a denominator, so first define what counts as a month in this application.

For the Ledger, use this rule:

Every month represented in the transaction history counts, even when that month has zero expenses.

The starter implementation filters zero-expense months away:

javascript
const withExpense = months.filter((month) => month.expense > 0);

const average =
  withExpense.length === 0
    ? 0
    : withExpense.reduce(
        (sum, month) => sum + month.expense,
        0
      ) / withExpense.length;

That changes the meaning of the metric to “average among months with spending.” That is not the definition we want here.

Use every represented month:

javascript
const average =
  months.length === 0
    ? 0
    : months.reduce(
        (sum, month) => sum + month.expense,
        0
      ) / months.length;

Suppose the history contains:

text
January   $1,000
February  $0
March     $1,000

The average is:

text
($1,000 + $0 + $1,000) / 3 = $666.67

February remains in the denominator because it is still a month represented by the ledger history.

Keep this definition independent of the current money representation. Module 6 will replace decimal amount values with integer cents, but it will not change what “average monthly spend” means.

Test it

Create or edit records so the history contains two months with spending and one represented month with no expenses.

Verify that the Summary average divides by all three represented months.

Checkpoint

You can explain the metric in one sentence, and the code implements that definition rather than silently excluding zero-expense months.