Keep an Undo History with a Limit

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write a class UndoHistory that keeps the history of any value. new UndoHistory(initial, limit) starts with initial as the current value; limit is the most undo steps it keeps (no limit if it's left out), so once there are more, the oldest is forgotten. get() returns the current value. set(value) makes value current and clears anything that could be redone; setting a value that's the same as the current one (Object.is) does nothing at all. undo() goes back one step and redo() forward one step, and both return the current value afterwards; with nothing to undo or redo they change nothing. canUndo() and canRedo() return whether there's a step to go back or forward to.

Your code must pass

  • set records values and get returns the current one
  • Undo and redo step back and forward
  • A new set clears the redo steps
  • Does nothing when there's nothing to undo or redo
  • Keeps at most limit undo steps
  • Ignores setting the same value again