Full answer
Two common designs:
- Snapshots (state history): store
past: [],present,future: []of immutable states. Easy to build and verify, and works well when state is small or updates share structure (spread copies or an immutable library). Memory grows with each step, so cap the size. - Commands (the command pattern): each action is an object with
do()andundo()(or a patch and its inverse). Memory is small and large documents work, but every action needs a correct inverse, which is hard to get right.
Rules for either design:
- A new change after undo clears the
futurestack. This is what users expect in a linear history. Tree histories keep branches but need a more complex UI. - Undo and redo themselves must not be recorded as changes.
- Cap the history (for example 100 steps) and drop the oldest entries.
- Group related changes: typing characters should not produce one undo step per key. Use a
coalesceKeyand a time window, so consecutive changes with the same key within a short delay merge into one step. A pause, a different key, or an explicitcommit()starts a new step. - Not everything belongs in history: UI state such as scroll position or hover usually does not. Keep the history for document data.
- Skip no-op changes (the new state is the same reference as the old).
- Expose
canUndoandcanRedofor the buttons, plus keyboard shortcuts (Ctrl or Cmd with Z, and Shift to redo) that do not hijack text inputs which have their own undo. - Server sync: undo after saving usually creates a new change, not a rewind of the server history.
- Time and randomness should be injected so tests are stable.
Pitfall: mutating the state in place makes all stored snapshots point to the same object, so undo seems to do nothing. Always create new objects for new states.
function createHistory(initial, { limit = 100, windowMs = 500, now = Date.now } = {}) {
let past = [];
let present = initial;
let future = [];
let lastKey = null;
let lastTime = -Infinity;
return {
get state() { return present; },
get canUndo() { return past.length > 0; },
get canRedo() { return future.length > 0; },
get size() { return past.length; },
change(next, coalesceKey = null) {
if (Object.is(next, present)) return false;
const time = now();
const merge = coalesceKey !== null && coalesceKey === lastKey && time - lastTime <= windowMs && past.length > 0;
if (!merge) {
past.push(present);
if (past.length > limit) past.shift();
}
present = next;
future = [];
lastKey = coalesceKey;
lastTime = time;
return true;
},
undo() {
if (!past.length) return false;
future.push(present);
present = past.pop();
lastKey = null;
return true;
},
redo() {
if (!future.length) return false;
past.push(present);
present = future.pop();
lastKey = null;
return true;
},
commit() { lastKey = null; },
};
}
let clock = 0;
const history = createHistory({ text: '', bold: false }, { limit: 4, windowMs: 300, now: () => clock });
const type = (char, at) => {
clock = at;
history.change({ ...history.state, text: history.state.text + char }, 'typing');
};
type('H', 0); type('e', 100); type('y', 200);
console.log('fast typing is one step:', JSON.stringify(history.state), '| steps:', history.size);
type('!', 1000);
console.log('after a pause, a new step:', history.state.text, '| steps:', history.size);
history.change({ ...history.state, bold: true });
console.log('different change:', JSON.stringify(history.state), '| steps:', history.size);
history.undo();
console.log('undo:', JSON.stringify(history.state), '| canRedo:', history.canRedo);
history.undo();
console.log('undo again:', JSON.stringify(history.state));
history.redo();
console.log('redo:', JSON.stringify(history.state));
history.change({ text: 'new branch', bold: false });
console.log('new change clears redo:', history.canRedo, '| state:', history.state.text);
console.log('same reference is ignored:', history.change(history.state), '| steps:', history.size);
for (let i = 1; i <= 6; i++) history.change({ text: 'step ' + i, bold: false });
let undone = 0;
while (history.undo()) undone++;
console.log('limit of 4 keeps only 4 undo steps:', undone, '| oldest state reachable:', history.state.text);
const badHistory = createHistory({ items: [] });
badHistory.state.items.push('mutated in place');
badHistory.change(badHistory.state);
console.log('mutation breaks history (same reference, no step):', badHistory.canUndo);Run with Node.js v24.22.1 as js-195.js; two runs gave identical output. Output: fast typing is one step: {"text":"Hey","bold":false} | steps: 1 after a pause, a new step: Hey! | steps: 2 different change: {"text":"Hey!","bold":true} | steps: 3 undo: {"text":"Hey!","bold":false} | canRedo: true undo again: {"text":"Hey","bold":false} redo: {"text":"Hey!","bold":false} new change clears redo: false | state: new branch same reference is ignored: false | steps: 3 limit of 4 keeps only 4 undo steps: 4 | oldest state reachable: step 2 mutation breaks history (same reference, no step): false
Key points
- Snapshots use past, present, and future; commands store do and undo pairs.
- A new change clears the future; undo and redo are not recorded.
- Cap the history and merge rapid edits with a key and a time window.
- Keep only document data in history; skip no-op changes.
- Never mutate stored states; expose canUndo and canRedo.
Common mistakes
- Mutating the current state, so all snapshots share the same object.
- Recording undo and redo as changes.
- Creating one undo step per keystroke.
- Letting the history grow with no limit.
Follow-ups
- How would you implement undo with commands instead of snapshots?
- How would you undo changes in a collaborative document?
- What would a branching history look like?
Tips
- Describe past, present, and future before writing code.
- Mention grouping and limits; they show experience.
- Say why immutability is needed.