An undo and redo history stack
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(); // falseA fresh edit after undoing throws the redo branch away.
What it has to do
pushreturns the new current state and clears anything ahead of the cursor.undoat the oldest state returns that state instead of throwing.redowith nothing ahead returns the current state.canUndo()andcanRedo()describe whether a move is available.- Undo followed by push makes the redo branch unreachable.
Notes
- Every operation except
pushis O(1);pushis 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
pushis 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.
- 1.the newest pushed state is current
- 2.undo walks back and redo walks forward
- 3.undo at the oldest state stays put
- 4.pushing after an undo discards the redo branch
- 5.push returns the state it made current
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.