Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Implement undo and redo in JavaScript

93 Undo and redo, and the trap of storing references

fair

Build undo/redo for an editor: a past stack, a present, and a future. A new edit after an undo must discard the redo stack, and undo at the very beginning must be a harmless no-op rather than a crash. Then mutate a state object in place and see what undo hands back.

Stuck? Three hints, smallest first
  1. 1. Three pieces: past, present, future. Undo moves one item from past to future through the present.
  2. 2. A fresh edit clears future. That is the branch you just abandoned.
  3. 3. The stacks hold whatever references you gave them, so a snapshot has to be a new object.

The answer

function createHistory(initial) {
  const past = [];
  const future = [];
  let present = initial;
  return {
    get present() { return present; },
    commit(next) {
      past.push(present);
      present = next;
      future.length = 0;             // the redo branch is abandoned by a new edit
      return present;
    },
    undo() {
      if (past.length === 0) return present;
      future.push(present);
      present = past.pop();
      return present;
    },
    redo() {
      if (future.length === 0) return present;
      past.push(present);
      present = future.pop();
      return present;
    },
    get canUndo() { return past.length > 0; },
    get canRedo() { return future.length > 0; },
    get depth() { return { past: past.length, future: future.length }; },
  };
}

const editor = createHistory({ title: 'Invoice 001', totalKobo: 0 });
const atTheStart = [editor.canUndo, editor.canRedo];
const nothingToUndo = editor.undo();

editor.commit({ title: 'Invoice 001', totalKobo: 250000 });
editor.commit({ title: 'Invoice 001 (Lagos)', totalKobo: 250000 });
editor.commit({ title: 'Invoice 001 (Lagos)', totalKobo: 412500 });
const afterThreeEdits = editor.depth;

const undoneOnce = editor.undo();
const undoneTwice = editor.undo();
const redone = editor.redo();
const flags = [editor.canUndo, editor.canRedo];

editor.undo();                              // back to the second state
editor.commit({ title: 'Invoice 001 (Ikeja)', totalKobo: 250000 });
const futureDiscarded = editor.depth;
const nothingToRedo = editor.redo();

// The trap: the stacks hold references, not copies.
const shared = { title: 'Receipt', totalKobo: 100 };
const sloppy = createHistory(shared);
shared.totalKobo = 99999;                   // mutating the object the history is holding
sloppy.commit({ title: 'Receipt', totalKobo: 200 });
const undoneAfterMutation = sloppy.undo();

console.log('after three edits :', afterThreeEdits);
console.log('undo, undo, redo  :', redone.totalKobo, 'flags', flags);
console.log('edit after undo   :', futureDiscarded, '<- future gone');
console.log('mutated snapshot  :', undoneAfterMutation);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a fresh history cannot undo or redo, and undo is a harmless no-op', [atTheStart, nothingToUndo.totalKobo], [[false, false], 0]);
test('three edits leave three states behind and nothing ahead', afterThreeEdits, { past: 3, future: 0 });
test('undo walks backwards through the states in order', [undoneOnce.title, undoneTwice.totalKobo], ['Invoice 001 (Lagos)', 250000]);
test('redo walks forwards again', [redone.title, redone.totalKobo], ['Invoice 001 (Lagos)', 250000]);
test('with something on both sides, both flags are true', flags, [true, true]);
test('an edit after an undo discards the redo branch entirely', futureDiscarded, { past: 2, future: 0 });
test('so redo has nowhere to go and returns the present unchanged', nothingToRedo.title, 'Invoice 001 (Ikeja)');
test('and a state mutated in place is corrupted in the past too, because the stack held the reference', undoneAfterMutation, { title: 'Receipt', totalKobo: 99999 });

Past, present, future is the whole model, and it is worth writing out rather than reaching for a library. Undo is "push the present onto future, pop the past into present", redo is the mirror image, and both guard the empty case by returning the present rather than throwing — a disabled button and a no-op are the same thing to a user who pressed Ctrl+Z one time too many.

The sixth assertion is the rule people forget. Editing after an undo abandons the branch you had undone, so the future stack must be cleared; leaving it means redo jumps to a state that was never derived from the current one, and the document silently loses the edit in between.

The last assertion is the one that produces real bugs. The stacks store references, so a state object you mutate in place is the same object sitting in past, and undo faithfully returns the mutated version. Nothing warns you. Either commit fresh objects — { ...state, totalKobo: next }, which is what the reducer in exercise 92 does anyway — or freeze what you commit so an accidental write throws under strict mode instead of quietly rewriting history. What this leaves out is worth knowing: full snapshots are simple and fine for a form or a small document, and hopeless for anything large. Once a snapshot is expensive, you store the inverse operation per step instead — a command pattern — and undo applies the inverse rather than restoring a copy.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.