Skip to content

Commit 08a95c9

Browse files
committed
Add undo example
1 parent 135cc1c commit 08a95c9

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

JavaScript/2-undo.js

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

0 commit comments

Comments
 (0)