-
Notifications
You must be signed in to change notification settings - Fork 7
/
decorator.ts
82 lines (62 loc) · 1.56 KB
/
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
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
{
// * ---------------- declaration
function log(target, name, descriptor) {
var oldValue = descriptor.value;
descriptor.value = function() {
console.log(`Calling ${name} with`, arguments);
const result = oldValue.apply(this, arguments);
console.log(`Result is ${result}`);
return result;
};
return descriptor;
}
// * ---------------- usage
class Tool {
@log
add(a, b) {
console.log(this);
return a + b;
}
}
console.log(new Tool().add(1, 2));
}
// Calling add with [Arguments] { '0': 1, '1': 2 }
// Tool {}
// Result is 3
// 3
// * ------------------------------------------------ alternative
{
// * ---------------- HOF
const log = function(fn) {
return function(...args) {
console.log(`Calling ${fn.name} with`, arguments);
const result = fn.apply(this, args);
console.log(`Result is ${result}`);
return result;
};
};
// * ---------------- usage
class Tool {
add = log(function add(a, b) {
console.log(this);
return a + b;
});
}
console.log(new Tool().add(1, 2));
}
// * ------------------------------------------------ composition
{
// * ---------------- HOF
const withLog = function(fn) {
return function(...args) {
console.log(`Calling ${fn.name} with`, arguments);
const result = fn.apply(this, args);
console.log(`Result is ${result}`);
return result;
};
};
// * ---------------- usage
const add = (a, b) => a + b;
const addWithLog = withLog(add);
console.log(addWithLog(1, 2));
}