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
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func applyOnce(events []Event) int {
}
Worked examples
| Call | Result |
|---|---|
applyOnce([]Event{Event{Key: "a", Amount: 100}, Event{Key: "b", Amount: 50}, Event{Key: "a", Amount: 100}}) | 150 |
applyOnce([]Event{Event{Key: "a", Amount: 100}, Event{Key: "a", Amount: -100}}) | 100 |
applyOnce([]Event{Event{Key: "x", Amount: 7}}) | 7 |
applyOnce([]Event{}) | 0 |
Hint
Remember the keys you have already honoured.
Reference solution in Go
func applyOnce(events []Event) int {
seen := map[string]bool{}
total := 0
for _, e := range events {
if seen[e.Key] {
continue
}
seen[e.Key] = true
total += e.Amount
}
return total
}