Problems › TypeScript › data
Totals per category
A ledger groups every sale under its category so each bucket shows a single sum.
- Add the amounts of every sale under the same category.
- Every category that appears earns an entry in the result.
- The result is one running total per category.
sumPerCategory(sales: list<Sale>) → map<string, int>
Where you start
function sumPerCategory(sales: Sale[]): Record<string, number> {
}
Worked examples
| Call | Result |
|---|---|
sumPerCategory([{"category":"food","amount":10},{"category":"food","amount":15}]) | {"food":25} |
sumPerCategory([{"category":"a","amount":3},{"category":"b","amount":4},{"category":"a","amount":5}]) | {"a":8,"b":4} |
sumPerCategory([{"category":"x","amount":1}]) | {"x":1} |
sumPerCategory([{"category":"p","amount":0},{"category":"q","amount":-2}]) | {"p":0,"q":-2} |
Hint
Aggregate into a map keyed by category, adding each amount as you go.
Reference solution in TypeScript
function sumPerCategory(sales: Sale[]): Record<string, number> {
const result = new Map<string, number>();
for (const s of sales) {
if (result.has(s.category)) result.set(s.category, result.get(s.category)! + s.amount);
else result.set(s.category, s.amount);
}
return result;
}