-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path5-complex.js
More file actions
68 lines (57 loc) · 1.38 KB
/
5-complex.js
File metadata and controls
68 lines (57 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict';
class BankAccount {
constructor(name) {
this.name = name;
this.balance = 0;
}
getBalance() {
return this.balance;
}
available(amount) {
return this.balance >= amount;
}
withdraw(amount) {
this.balance -= amount;
}
income(amount) {
this.balance += amount;
}
}
class Bank {
constructor() {
this.accounts = new Map();
}
transfer(from, to, amount) {
const source = this.accounts.get(from);
const destination = this.accounts.get(to);
if (!source || !destination) return false;
if (!source.available(amount)) return false;
source.withdraw(amount);
destination.income(amount);
return true;
}
total() {
let sum = 0;
for (const account of this.accounts.values()) {
const balance = account.getBalance();
sum += balance;
}
return sum;
}
openAccount(name, amount = 0) {
if (this.accounts.get(name)) return false;
const account = new BankAccount(name);
this.accounts.set(name, account);
if (amount) account.income(amount);
return true;
}
}
// Usage
const bank = new Bank();
bank.openAccount('Marcus Aurelius');
bank.openAccount('Antoninus Pius', 1000);
const total1 = bank.total();
console.log('Total before transfer:', total1);
bank.transfer('Antoninus Pius', 'Marcus Aurelius', 50);
const total2 = bank.total();
console.log('Total after transfer:', total2);