-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path1-simple.js
More file actions
98 lines (83 loc) · 2.32 KB
/
1-simple.js
File metadata and controls
98 lines (83 loc) · 2.32 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
class AccountCommand {
constructor(account, operation, amount) {
this.operation = operation;
this.account = account;
this.amount = amount;
}
}
class AccountQuery {
constructor(account, operation) {
this.account = account;
this.operation = operation;
this.rows = 0;
}
}
class BankAccount {
static collection = new Map();
constructor(name) {
this.name = name;
this.balance = 0;
BankAccount.collection.set(name, this);
}
static find(name) {
return BankAccount.collection.get(name);
}
}
const OPERATIONS = {
withdraw: (command) => {
const account = BankAccount.find(command.account);
account.balance -= command.amount;
},
income: (command) => {
const account = BankAccount.find(command.account);
account.balance += command.amount;
},
};
class Bank {
constructor() {
this.commands = [];
this.queries = [];
}
operation(account, value) {
const operation = value < 0 ? 'withdraw' : 'income';
const execute = OPERATIONS[operation];
const amount = Math.abs(value);
const command = new AccountCommand(account.name, operation, amount);
this.commands.push(command);
console.dir(command);
execute(command);
}
select({ account, operation }) {
const query = new AccountQuery(account, operation);
this.queries.push(query);
const result = [];
for (const command of this.commands) {
let condition = true;
if (account) condition = command.account === account;
if (operation) condition = condition && command.operation === operation;
if (condition) result.push(command);
}
query.rows = result.length;
console.dir(query);
return result;
}
}
// Usage
const bank = new Bank();
const account1 = new BankAccount('Marcus Aurelius');
bank.operation(account1, 1000);
bank.operation(account1, -50);
const account2 = new BankAccount('Antoninus Pius');
bank.operation(account2, 500);
bank.operation(account2, -100);
bank.operation(account2, 150);
console.table([account1, account2]);
const res1 = bank.select({ account: 'Marcus Aurelius' });
console.table(res1);
const res2 = bank.select({ account: 'Antoninus Pius', operation: 'income' });
console.table(res2);
const res3 = bank.select({ operation: 'withdraw' });
console.table(res3);
console.log('Query logs:');
console.table(bank.queries);