Command history with undo, redo, and grouped batch steps
A spreadsheet app does not store a snapshot of the whole sheet for every edit. Instead, every edit is a command that knows how to apply itself and how to revert itself. Undo calls revert, redo calls apply again. Some user actions, like “paste 3 cells”, run several commands that must undo as one step.
Implement a class CommandHistory that runs commands and manages their undo and redo.
const history = new CommandHistory();
history.execute(command) // runs command.apply() and records it; returns what apply() returned
history.undo() // => boolean: reverts the latest step
history.redo() // => boolean: re-applies the latest undone step
history.canUndo() // => boolean
history.canRedo() // => boolean
history.group(fn) // runs fn(); every command executed inside becomes one step; returns fn's return value
A command is an object { apply(), revert() }. Call both as methods (command.apply()), so this is the command.
execute(command) calls command.apply(). If it returns, record the command as a new undo step, clear the redo history, and return its return value.apply() throws, rethrow the error and leave the history exactly as it was (the redo history is kept too).undo(): if there is no step to undo, return false. Otherwise call revert() on every command of the latest step, in reverse order, move the step to the redo history, and return true.redo(): if there is no step to redo, return false. Otherwise call apply() on every command of that step, in the original order, move it back to the undo history, and return true.group(fn) calls fn(). All commands that execute successfully during that call form a single step, recorded when fn returns.
fn throws, call revert() on the commands the group already applied (in reverse order), record nothing, and rethrow. For a nested group that throws, roll back only that inner group’s commands; if the outer fn catches the error, the outer group continues.fn catches that error, the group continues normally.undo() or redo() while a group is running throws an Error and changes nothing.revert() and re-running apply() during undo and redo never throw.const cells = { A1: '', A2: '' };
const setCell = (key, value) => {
let previous;
return {
apply() { previous = cells[key]; cells[key] = value; return value; },
revert() { cells[key] = previous; },
};
};
const history = new CommandHistory();
history.execute(setCell('A1', 'Rent')); // => 'Rent'
history.group(() => {
history.execute(setCell('A1', 'Food'));
history.execute(setCell('A2', '120'));
});
// cells: { A1: 'Food', A2: '120' }
history.undo(); // => true, cells: { A1: 'Rent', A2: '' } (the whole group)
history.undo(); // => true, cells: { A1: '', A2: '' }
history.undo(); // => false
history.redo(); // => true, cells: { A1: 'Rent', A2: '' }
history.canRedo(); // => true
history.execute(setCell('A2', '99')); // clears the redo history
history.canRedo(); // => false