export class Lookup<Factory, Instance> {
protected readonly factories = new WeakMap<any, Record<string, Factory | null>>();
protected readonly instances = new WeakMap<any, Record<string, Instance | null>>();
constructor(private readonly lookupFactory?: () => Factory | undefined) {}
getInstance(thisArg: any, name: string, create: () => Instance | undefined): Instance | undefined {
let map = this.instances.get(thisArg);
Eif (!map) {
map = {};
this.instances.set(this, map);
}
let instance = map ? map[name] : undefined;
Eif (instance === undefined) {
instance = create();
map[name] = instance || null;
}
return instance || undefined;
}
getFactory(thisArg: any, name: string, prefer?: Factory): Factory | undefined {
let map = this.factories.get(thisArg);
Eif (!map) {
map = {};
this.factories.set(this, map);
}
let factory: Factory | null | undefined = prefer || map[name];
Eif (factory === undefined && this.lookupFactory) {
factory = this.lookupFactory();
map[name] = factory || null;
}
return factory || undefined;
}
}
|