|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +class AccountCommand { |
| 4 | + constructor(operation, account, amount) { |
| 5 | + this.operation = operation; |
| 6 | + this.account = account; |
| 7 | + this.amount = amount; |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +class BankAccount { |
| 12 | + constructor(name) { |
| 13 | + this.name = name; |
| 14 | + this.balance = 0; |
| 15 | + BankAccount.collection.set(name, this); |
| 16 | + } |
| 17 | + static find(name) { |
| 18 | + return BankAccount.collection.get(name); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +BankAccount.collection = new Map(); |
| 23 | + |
| 24 | +const operations = { |
| 25 | + Withdraw: { |
| 26 | + execute: command => { |
| 27 | + const account = BankAccount.find(command.account); |
| 28 | + account.balance -= command.amount; |
| 29 | + }, |
| 30 | + undo: command => { |
| 31 | + const account = BankAccount.find(command.account); |
| 32 | + account.balance += command.amount; |
| 33 | + }, |
| 34 | + }, |
| 35 | + Income: { |
| 36 | + execute: command => { |
| 37 | + const account = BankAccount.find(command.account); |
| 38 | + account.balance += command.amount; |
| 39 | + }, |
| 40 | + undo: command => { |
| 41 | + const account = BankAccount.find(command.account); |
| 42 | + account.balance -= command.amount; |
| 43 | + }, |
| 44 | + }, |
| 45 | +}; |
| 46 | + |
| 47 | +class Bank { |
| 48 | + constructor() { |
| 49 | + this.commands = []; |
| 50 | + } |
| 51 | + operation(account, amount) { |
| 52 | + const operation = amount < 0 ? 'Withdraw' : 'Income'; |
| 53 | + const { execute } = operations[operation]; |
| 54 | + const command = new AccountCommand( |
| 55 | + operation, account.name, Math.abs(amount) |
| 56 | + ); |
| 57 | + this.commands.push(command); |
| 58 | + execute(command); |
| 59 | + } |
| 60 | + undo(count) { |
| 61 | + for (let i = 0; i < count; i++) { |
| 62 | + const command = this.commands.pop(); |
| 63 | + const operation = command.amount < 0 ? 'Withdraw' : 'Income'; |
| 64 | + const { undo } = operations[operation]; |
| 65 | + undo(command); |
| 66 | + } |
| 67 | + } |
| 68 | + showOperations() { |
| 69 | + console.table(this.commands); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// Usage |
| 74 | + |
| 75 | +const bank = new Bank(); |
| 76 | +const account1 = new BankAccount('Marcus Aurelius'); |
| 77 | +bank.operation(account1, 1000); |
| 78 | +bank.operation(account1, -50); |
| 79 | +const account2 = new BankAccount('Antoninus Pius'); |
| 80 | +bank.operation(account2, 500); |
| 81 | +bank.operation(account2, -100); |
| 82 | +bank.operation(account2, 150); |
| 83 | +bank.showOperations(); |
| 84 | +console.table([account1, account2]); |
| 85 | +bank.undo(2); |
| 86 | +bank.showOperations(); |
| 87 | +console.table([account1, account2]); |
0 commit comments