Run and Undo Typed Commands

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

The problem

  • medium
  • Code

Use the command pattern. Export an interface Command<T> with execute(target) and undo(target), and a class History<T>, created with the target the commands act on. run(command) executes a command on the target and remembers it; undo(count = 1) undoes the last count commands, newest first, and returns how many it undid (fewer when the history runs out). Type it so a command must have both methods, receives the target's type, and can't be run on a history for a different kind of target.

Your code must pass

  • Runs each command on the target
  • Undoes the last commands, newest first
  • Stops at the start of the history
  • Has no type errors
  • Commands get the target's type
  • A command must have undo
  • Rejects a command for another kind of target