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.
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.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.