-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProxyStats.js
More file actions
82 lines (63 loc) · 1.99 KB
/
ProxyStats.js
File metadata and controls
82 lines (63 loc) · 1.99 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
class ProxyStats {
static _instances = {};
constructor() {
this._timers = {};
this.stats = {};
}
static watch(target, name) {
if (name === undefined) {
return new Proxy(target, new ProxyStats());
}
this._instances[name] = this._instances[name] || new ProxyStats(name);
return this._instances[name].watch(target);
}
watch(target) {
return new Proxy(target, this)
}
time(key) {
this._timers[key] = this._timers[key] || [];
this._timers[key].push(Date.now());
return key;
}
timeEnd(key) {
const time = Date.now() - this._timers[key].pop();
if (this._timers[key].length === 0) {
this.updateStats(key, time);
console.log(key, `${time} ms (${this.stats[key].time} ms -- ${this.stats[key].count})`);
} else {
this.updateStats(key, 0);
console.log(key, `${time} ms (${this.stats[key].time + time} ms -- ${this.stats[key].count})`);
}
}
updateStats(key, time) {
this.stats[key] = this.stats[key] || {time: 0, count: 0};
this.stats[key].time += time;
this.stats[key].count += 1;
}
handleFunction(target, property, receiver) {
const me = this;
return new Proxy(target[property], {
apply(fnTarget, thisArg, args) {
const timeKey = me.time(`${target.constructor.name}.${property}()`);
const result = Reflect.apply(fnTarget, thisArg, args);
me.timeEnd(timeKey);
return result;
}
});
}
get(target, property, receiver) {
if (typeof target[property] === 'function') {
return this.handleFunction(target, property, receiver);
}
const timeKey = this.time(`get ${target.constructor.name}.${property}`);
const result = Reflect.get(target, property, receiver);
this.timeEnd(timeKey);
return result;
}
set(target, property, value, receiver) {
const timeKey = this.time(`set ${target.constructor.name}.${property}`);
Reflect.set(target, property, value, receiver);
this.timeEnd(timeKey);
return true;
}
}