-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethod-decorator.ts
44 lines (38 loc) · 1.09 KB
/
method-decorator.ts
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
const methodToKeyMap = {
withdrawFromAccountA: "accountA",
withdrawFromAccountB: "accountB",
};
const minimumAmount = (amount: number) => {
return (
target: Object,
propertyKey: string,
descriptor: PropertyDescriptor
) => {
const originalFn = descriptor.value;
descriptor.value = function (...args: any) {
if (this[methodToKeyMap[propertyKey]] - args[0] > amount) {
originalFn.call(this, args);
} else {
console.log(`${methodToKeyMap[propertyKey]}: Not enough money`);
}
};
return descriptor;
};
};
class BankMethodDecorator {
accountA: number = 200;
accountB: number = 1000;
@minimumAmount(100)
withdrawFromAccountA(amount: number) {
this.accountA = this.accountA - amount;
}
@minimumAmount(200)
withdrawFromAccountB(amount: number) {
this.accountB = this.accountB - amount;
}
}
const bankMethodDecorator = new BankMethodDecorator();
bankMethodDecorator.withdrawFromAccountA(200);
bankMethodDecorator.withdrawFromAccountB(200);
console.log(bankMethodDecorator.accountA);
console.log(bankMethodDecorator.accountB);