|
| 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 | +} |
| 18 | + |
| 19 | +BankAccount.collection = new Map(); |
| 20 | + |
| 21 | +const operations = { |
| 22 | + Withdraw: command => { |
| 23 | + const account = BankAccount.collection.get(command.account); |
| 24 | + account.balance -= command.amount; |
| 25 | + }, |
| 26 | + Income: command => { |
| 27 | + const account = BankAccount.collection.get(command.account); |
| 28 | + account.balance += command.amount; |
| 29 | + }, |
| 30 | + Allowed: command => { |
| 31 | + if (command.operation === 'Income') return true; |
| 32 | + const account = BankAccount.collection.get(command.account); |
| 33 | + return account.balance >= command.amount; |
| 34 | + }, |
| 35 | +}; |
| 36 | + |
| 37 | +class Bank { |
| 38 | + constructor() { |
| 39 | + this.commands = []; |
| 40 | + } |
| 41 | + operation(account, amount) { |
| 42 | + const operation = amount < 0 ? 'Withdraw' : 'Income'; |
| 43 | + const execute = operations[operation]; |
| 44 | + const command = new AccountCommand( |
| 45 | + operation, account.name, Math.abs(amount) |
| 46 | + ); |
| 47 | + const allowed = operations.Allowed(command); |
| 48 | + if (!allowed) { |
| 49 | + const target = BankAccount.collection.get(command.account); |
| 50 | + throw new Error( |
| 51 | + 'Command is not allowed:\n' + JSON.stringify(command) + |
| 52 | + '\non ' + JSON.stringify(target) |
| 53 | + ); |
| 54 | + } |
| 55 | + this.commands.push(command); |
| 56 | + execute(command); |
| 57 | + } |
| 58 | + showOperations() { |
| 59 | + console.table(this.commands); |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// Usage |
| 64 | + |
| 65 | +const bank = new Bank(); |
| 66 | +const account1 = new BankAccount('Marcus Aurelius'); |
| 67 | +bank.operation(account1, 1000); |
| 68 | +bank.operation(account1, -50); |
| 69 | +const account2 = new BankAccount('Antoninus Pius'); |
| 70 | +bank.operation(account2, 500); |
| 71 | +bank.operation(account2, -100); |
| 72 | +bank.operation(account2, 150); |
| 73 | +bank.showOperations(); |
| 74 | +console.table([account1, account2]); |
0 commit comments