Problems › JavaScript › patterns
Replay a log that can take it back
A stock adjustment screen records every change, and an undo command that cancels whichever change came last.
- A command is either a signed whole number to apply, or the word "undo".
- An undo cancels the most recent change that is still standing.
- An undo with nothing left to cancel does nothing.
- Start from zero and return the total once every command has run.
replayLog(commands: list<string>) → int
Where you start
function replayLog(commands) {
}
Worked examples
| Call | Result |
|---|---|
replayLog(["5","3","undo"]) | 5 |
replayLog(["5","undo","undo"]) | 0 |
replayLog(["10","-4","2"]) | 8 |
replayLog([]) | 0 |
Hint
Keep the applied changes on a stack. Undo pops the last one off and subtracts it back out.
Reference solution in JavaScript
function replayLog(commands) {
const applied = [];
let total = 0;
for (const command of commands) {
if (command === "undo") {
if (applied.length > 0) total -= applied.pop();
} else {
const amount = parseInt(command, 10);
applied.push(amount);
total += amount;
}
}
return total;
}