javascriptintermediate10 minutes

Refactor a Function to Cleanly Aggregate User Purchases

The provided JavaScript function processes an array of user purchase objects to calculate total spending per user. The existing code works but is messy and repetitive. Refactor it for clarity, reusability, and improved readability without changing its behavior.

Challenge prompt

You are given a function that takes an array of purchase objects. Each object has two properties: userId (string) and amount (number). The function processes the array and returns an object mapping each userId to the total sum of their purchases. Your task is to refactor the function to improve its readability, reduce repetition, and adhere to best code practices while keeping the exact same output and behavior. Do not change how the function handles invalid or missing data (assume input is valid).

Guidance

  • Break down complex loops or repeated code into smaller helper functions if needed.
  • Use descriptive variable names and avoid unnecessary temporary variables.
  • Aim for clear and concise logic using JavaScript array methods to improve readability.

Hints

  • Consider using Array.prototype.reduce() to accumulate totals.
  • Avoid mutating the input array; build the output immutably if possible.
  • You can use object destructuring to access properties cleanly.

Starter code

function calculateTotals(purchases) {
  let totals = {};
  for (let i = 0; i < purchases.length; i++) {
    let user = purchases[i].userId;
    let amount = purchases[i].amount;
    if (totals[user] === undefined) {
      totals[user] = 0;
    }
    totals[user] = totals[user] + amount;
  }
  return totals;
}

Expected output

calculateTotals([{ userId: 'alice', amount: 30 }, { userId: 'bob', amount: 20 }, { userId: 'alice', amount: 10 }]) // returns { alice: 40, bob: 20 }

Core concepts

JavaScript arraysObject manipulationArray reduce methodCode readability

Challenge a Friend

Send this duel to someone else and see if they can solve it.