sdfxs

Untitled

Jun 15th, 2021
848
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface Command {
  2.     execute(value: number): number;
  3.     undo(value: number): number;
  4. }
  5.  
  6. class Calculator {
  7.   public value: number;
  8.   private history: Command[];
  9.   constructor(initialValue: number) {
  10.     this.value = initialValue
  11.     this.history = []
  12.   }
  13.  
  14.   executeCommand(command: Command) {
  15.     this.value = command.execute(this.value)
  16.     this.history.push(command)
  17.   }
  18.  
  19.   undo() {
  20.     const command = this.history.pop()
  21.     if (command) {
  22.         this.value = command.undo(this.value)
  23.     }
  24.   }
  25. }
  26.  
  27. class AddCommand implements Command {
  28.   private valueToAdd: number;
  29.   constructor(valueToAdd: number) {
  30.     this.valueToAdd = valueToAdd
  31.   }
  32.  
  33.   execute(currentValue: number) {
  34.     return currentValue + this.valueToAdd
  35.   }
  36.  
  37.   undo(currentValue: number) {
  38.     return currentValue - this.valueToAdd
  39.   }
  40. }
  41.  
  42. class SubtractCommand implements Command {
  43.   private valueToSubtract: number;
  44.   constructor(valueToSubtract: number) {
  45.     this.valueToSubtract = valueToSubtract
  46.   }
  47.  
  48.   execute(currentValue: number) {
  49.     return currentValue - this.valueToSubtract
  50.   }
  51.  
  52.   undo(currentValue: number) {
  53.     return currentValue + this.valueToSubtract
  54.   }
  55. }
  56.  
  57. class MultiplyCommand implements Command {
  58.   private valueToMultiply: number;
  59.   constructor(valueToMultiply: number) {
  60.     this.valueToMultiply = valueToMultiply
  61.   }
  62.  
  63.   execute(currentValue: number) {
  64.     return currentValue * this.valueToMultiply
  65.   }
  66.  
  67.   undo(currentValue: number) {
  68.     return currentValue / this.valueToMultiply
  69.   }
  70. }
  71.  
  72. class DivideCommand implements Command {
  73.   private valueToDivide: number;
  74.   constructor(valueToDivide: number) {
  75.     this.valueToDivide = valueToDivide
  76.   }
  77.  
  78.   execute(currentValue: number) {
  79.     return currentValue / this.valueToDivide
  80.   }
  81.  
  82.   undo(currentValue: number) {
  83.     return currentValue * this.valueToDivide
  84.   }
  85. }
  86.  
  87. const calculator  = new Calculator(0);
  88. calculator.executeCommand(new AddCommand(10))
  89. calculator.executeCommand(new MultiplyCommand(2))
  90. console.log(calculator.value)
  91. calculator.undo()
  92. console.log(calculator.value)
RAW Paste Data