-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
97 lines (79 loc) · 1.97 KB
/
mod.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*!
* Based on https://github.com/tj/node-delegates/blob/master/index.js
* Copyright (c) 2015 TJ Holowaychuk <[email protected]>
* Copyright (c) 2020 Henry Zhuang
* MIT Licensed
*/
export function delegates(proto: any, target: string): Delegator {
return new Delegator(proto, target);
}
export class Delegator {
private proto: any;
private target: string;
private methods: string[] = [];
private getters: string[] = [];
private setters: string[] = [];
constructor(proto: any, target: string) {
this.proto = proto;
this.target = target;
}
/**
* Delegate method `name`.
*
* @param {String} name
* @return {Delegator} self
* @api public
*/
method(name: string): Delegator {
const proto = this.proto as any;
const target = this.target;
this.methods.push(name);
proto[name] = function (...argv: any) {
return this[target][name].apply(this[target], argv);
};
return this;
}
/**
* Delegator accessor `name`.
*
* @param {String} name
* @return {Delegator} self
* @api public
*/
access(name: string) {
return this.getter(name).setter(name);
}
/**
* Delegator getter `name`.
*
* @param {String} name
* @return {Delegator} self
* @api public
*/
getter(name: string): Delegator {
const proto = this.proto as any;
const target = this.target;
this.getters.push(name);
// https://github.com/Microsoft/TypeScript/issues/16016
proto.__defineGetter__(name, function (this: any) {
return this[target] ? this[target][name] : undefined;
});
return this;
}
/**
* Delegator setter `name`.
*
* @param {String} name
* @return {Delegator} self
* @api public
*/
setter(name: string): Delegator {
const proto = this.proto as any;
const target = this.target;
this.setters.push(name);
proto.__defineSetter__(name, function (this: any, val: any) {
return this[target][name] = val;
});
return this;
}
}