HardPro challengeJavaScriptTypeScript

Undo / Redo Stack

ReactPatternsState

Implement an undo/redo manager:

  • push(state) — add new state, clear redo stack.
  • undo() — return previous state.
  • redo() — return forward state.

solve(initial, ops) returns the value after each op.
Ops: { type: 'push', value }, { type: 'undo' }, { type: 'redo' }.

Sample tests

Test #1No ops
Input: [5,[]]
Output: []
Test #2Two pushes, one undo
Input: [0,[{"type":"push","value":1},{"type":"push","value":2},{"type":"undo"}]]
Output: [1,2,1]
Test #3Undo then redo
Input: [0,[{"type":"push","value":1},{"type":"undo"},{"type":"redo"}]]
Output: [1,0,1]
Test #4Undo with empty past
Input: [10,[{"type":"undo"}]]
Output: [10]
Test #5Push after undo clears future
Input: [0,[{"type":"push","value":1},{"type":"push","value":2},{"type":"undo"},{"type":"push","value":3},{"type":"redo"}]]
Output: [1,2,1,3,3]