AniUI Academy

An undo and redo history stack

mediumData Structures+250 XPPractice

Every editor keeps a timeline of states with a cursor pointing at the current one. Undo steps the cursor back, redo steps it forward, and — the part people forget — making a fresh edit after undoing discards everything ahead of the cursor.

Implement a History class. new History(initial) starts with one recorded state, initial, as the current state. push(state) records a new state, makes it current, discards any states that were ahead of the cursor, and returns the new current state. undo() moves the cursor back one step and returns the now-current state; if it is already at the oldest state it stays there and returns that state. redo() moves the cursor forward one step and returns the now-current state; if there is nothing ahead it stays and returns the current state. current() returns the current state. canUndo() returns true when there is an older state, and canRedo() returns true when there is a newer one.

Examples

const h = new History("a");
h.push("b");
h.push("c");
h.undo();   // "b"
h.undo();   // "a"
h.redo();   // "b"
const h = new History("a");
h.push("b");
h.undo();     // "a"
h.push("z");  // "z" — the redo branch to "b" is now gone
h.canRedo();  // false

A fresh edit after undoing throws the redo branch away.

What it has to do

  • push returns the new current state and clears anything ahead of the cursor.
  • undo at the oldest state returns that state instead of throwing.
  • redo with nothing ahead returns the current state.
  • canUndo() and canRedo() describe whether a move is available.
  • Undo followed by push makes the redo branch unreachable.

Notes

  • Every operation except push is O(1); push is O(k) only when it has to truncate k redo entries.
  • A single array plus a cursor is enough — no need for two stacks. Truncating at the cursor on push is what makes the redo branch unreachable.
  • Keeping arbitrary state snapshots can grow unboundedly. Real editors cap history or store diffs instead of full states.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.