-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
lazy-helpers.ts
56 lines (51 loc) · 1.49 KB
/
lazy-helpers.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
import constructor from "./types/constructor.ts";
export class DelayedConstructor<T> {
private reflectMethods: ReadonlyArray<keyof ProxyHandler<any>> = [
"get",
"getPrototypeOf",
"setPrototypeOf",
"getOwnPropertyDescriptor",
"defineProperty",
"has",
"set",
"deleteProperty",
"apply",
"construct",
];
constructor(private wrap: () => constructor<T>) {}
public createProxy(createObject: (ctor: constructor<T>) => T): T {
const target: object = {};
let init = false;
let value: T;
const delayedObject: () => T = (): T => {
if (!init) {
value = createObject(this.wrap());
init = true;
}
return value;
};
return new Proxy<any>(target, this.createHandler(delayedObject)) as T;
}
private createHandler(delayedObject: () => T): ProxyHandler<object> {
const handler: ProxyHandler<object> = {};
const install = (name: keyof ProxyHandler<any>): void => {
handler[name] = (...args: any[]) => {
args[0] = delayedObject();
const method = Reflect[name];
return (method as any)(...args);
};
};
this.reflectMethods.forEach(install);
return handler;
}
}
export function delay<T>(
wrappedConstructor: () => constructor<T>,
): DelayedConstructor<T> {
if (typeof wrappedConstructor === "undefined") {
throw new Error(
"Attempt to `delay` undefined. Constructor must be wrapped in a callback",
);
}
return new DelayedConstructor<T>(wrappedConstructor);
}