Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface Command {
- execute(value: number): number;
- undo(value: number): number;
- }
- class Calculator {
- public value: number;
- private history: Command[];
- constructor(initialValue: number) {
- this.value = initialValue
- this.history = []
- }
- executeCommand(command: Command) {
- this.value = command.execute(this.value)
- this.history.push(command)
- }
- undo() {
- const command = this.history.pop()
- if (command) {
- this.value = command.undo(this.value)
- }
- }
- }
- class AddCommand implements Command {
- private valueToAdd: number;
- constructor(valueToAdd: number) {
- this.valueToAdd = valueToAdd
- }
- execute(currentValue: number) {
- return currentValue + this.valueToAdd
- }
- undo(currentValue: number) {
- return currentValue - this.valueToAdd
- }
- }
- class SubtractCommand implements Command {
- private valueToSubtract: number;
- constructor(valueToSubtract: number) {
- this.valueToSubtract = valueToSubtract
- }
- execute(currentValue: number) {
- return currentValue - this.valueToSubtract
- }
- undo(currentValue: number) {
- return currentValue + this.valueToSubtract
- }
- }
- class MultiplyCommand implements Command {
- private valueToMultiply: number;
- constructor(valueToMultiply: number) {
- this.valueToMultiply = valueToMultiply
- }
- execute(currentValue: number) {
- return currentValue * this.valueToMultiply
- }
- undo(currentValue: number) {
- return currentValue / this.valueToMultiply
- }
- }
- class DivideCommand implements Command {
- private valueToDivide: number;
- constructor(valueToDivide: number) {
- this.valueToDivide = valueToDivide
- }
- execute(currentValue: number) {
- return currentValue / this.valueToDivide
- }
- undo(currentValue: number) {
- return currentValue * this.valueToDivide
- }
- }
- const calculator = new Calculator(0);
- calculator.executeCommand(new AddCommand(10))
- calculator.executeCommand(new MultiplyCommand(2))
- console.log(calculator.value)
- calculator.undo()
- console.log(calculator.value)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement