call(back)
FrontendmediumSign in to star problems

Undo/Redo Manager

Write a class UndoRedo that tracks a single value's history:

  • new UndoRedo(initial) starts with initial as the current value.
  • set(value) makes value current and discards any redo history.
  • undo() restores the previous value and returns it, or returns null and changes nothing when there is nothing to undo.
  • redo() re-applies the most recently undone value and returns it, or null when there is nothing to redo.
  • value(), canUndo(), canRedo() report the state.
const history = new UndoRedo("a");
history.set("b"); history.set("c");
history.undo();   // "b"
history.redo();   // "c"
history.undo(); history.set("d");
history.canRedo();   // false — the set cleared it

Hints

Hint 1

Keep current, an undo stack of past values and a redo stack of undone ones.

Hint 2

set pushes the current value onto undo and empties redo; undo pushes current onto redo and pops undo; redo is the mirror image.

Asked at