Problems › TypeScript › reporting
Running balance down a statement
An account statement shows the balance after every movement, not just the final figure.
- The result is the same length as the input.
- Each entry is the sum of everything up to and including that position.
runningTotal(amounts: list<int>) → list<int>
Where you start
function runningTotal(amounts: number[]): number[] {
}
Worked examples
| Call | Result |
|---|---|
runningTotal([1,2,3]) | [1,3,6] |
runningTotal([5,-5,5]) | [5,0,5] |
runningTotal([7]) | [7] |
runningTotal([]) | [] |
Hint
Carry one accumulator down the list and push it after each step.
Reference solution in TypeScript
function runningTotal(amounts: number[]): number[] {
let sum = 0;
const result: number[] = [];
for (const a of amounts) {
sum += a;
result.push(sum);
}
return result;
}