Problems › TypeScript › payments
Charge each request only once
The payment webhook is delivered at least once, sometimes more. Each delivery carries an idempotency key, and a replay must not charge the customer twice.
- Sum the amounts, but only the first event carrying a given key counts.
- A later event with a key already seen is a replay, whatever amount it claims.
applyOnce(events: list<Event>) → int
Where you start
function applyOnce(events: Event[]): number {
}
Worked examples
| Call | Result |
|---|---|
applyOnce([{"key":"a","amount":100},{"key":"b","amount":50},{"key":"a","amount":100}]) | 150 |
applyOnce([{"key":"a","amount":100},{"key":"a","amount":-100}]) | 100 |
applyOnce([{"key":"x","amount":7}]) | 7 |
applyOnce([]) | 0 |
Hint
Remember the keys you have already honoured.
Reference solution in TypeScript
function applyOnce(events: Event[]): number {
const seen = new Set<string>();
let total = 0;
for (const e of events) {
if (seen.has(e.key)) continue;
seen.add(e.key);
total += e.amount;
}
return total;
}