Bridge · From syntax to engineering · 25 MIN
Aggregate without mutating the input
Separate reading data from changing your result.
A reducer is a function that combines records into one result. A Map keeps arbitrary category names, including __proto__, separate from object prototypes. Traverse the input once and update only your own accumulator. Object.fromEntries converts that accumulator into the requested JSON object. This makes ownership clear: callers can reuse the input without discovering that your function changed it. In a payment system, use integer minor units and validate their range at the input boundary.
Write a small contract first, then test how the implementation behaves at its boundaries.
Read the example
const totals = new Map();
totals.set("books", (totals.get("books") ?? 0) + 12);
console.log(totals.get("books"));Check the expected output
12
Your challenge
Input is an array of {category:string, amount:integer}. Return an object containing the total per category. Keep zero and negative adjustments. Do not change the input.
Solution cost: Expected O(n) for n records. time · O(c) for c categories. space
Common trap
Using {} as an unchecked dictionary can treat inherited property names as existing values.
Further reading: MDN Map
Next lesson: Find the first matching value with binary search →