Skip to content

Commit 85d90c0

Browse files
committed
Add JavaScript way
1 parent 82d0ab7 commit 85d90c0

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

JavaScript/6-js-way.js

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

0 commit comments

Comments
 (0)