Drill

ProblemsJavaScript › payments

Charge each request only once

mediumpaymentsJavaScript

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.

applyOnce(events: list<Event>) → int

Solve it in the editor →

Where you start

function applyOnce(events) {
  
}

Worked examples

CallResult
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 JavaScript
function applyOnce(events) {
  const seen = new Set();
  let total = 0;
  for (const e of events) {
    if (seen.has(e.key)) continue;
    seen.add(e.key);
    total += e.amount;
  }
  return total;
}

The same problem in another language

More payments problems in JavaScript