2022-02-27 22:58:41 +08:00
|
|
|
export interface RegistryOptions {
|
|
|
|
override: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class Registry<T> {
|
|
|
|
private map = new Map<string, T>();
|
|
|
|
options: RegistryOptions;
|
|
|
|
|
|
|
|
constructor(options: RegistryOptions = { override: false }) {
|
|
|
|
this.options = options;
|
|
|
|
}
|
|
|
|
|
2023-02-21 20:12:21 +08:00
|
|
|
public register(key: string, value: T): void {
|
2022-02-27 22:58:41 +08:00
|
|
|
if (!this.options.override && this.map.has(key)) {
|
|
|
|
throw new Error(`this registry does not allow to override existing keys: "${key}"`);
|
|
|
|
}
|
|
|
|
|
|
|
|
this.map.set(key, value);
|
|
|
|
}
|
|
|
|
|
|
|
|
// async import({ directory, extensions = ['.js', '.ts', '.json'] }) {
|
|
|
|
// const files = await fs.readdir(directory);
|
|
|
|
// return files.filter(file => extensions.includes(path.extname(file)))
|
|
|
|
// }
|
|
|
|
|
2023-02-21 20:12:21 +08:00
|
|
|
public get(key: string): T {
|
2022-02-27 22:58:41 +08:00
|
|
|
return this.map.get(key);
|
|
|
|
}
|
|
|
|
|
2023-02-21 20:12:21 +08:00
|
|
|
public getKeys(): Iterable<string> {
|
2022-03-27 15:51:48 +08:00
|
|
|
return this.map.keys();
|
|
|
|
}
|
|
|
|
|
2023-02-21 20:12:21 +08:00
|
|
|
public getValues(): Iterable<T> {
|
2022-02-27 22:58:41 +08:00
|
|
|
return this.map.values();
|
|
|
|
}
|
|
|
|
|
2023-02-21 20:12:21 +08:00
|
|
|
public getEntities(): Iterable<[string, T]> {
|
2022-02-27 22:58:41 +08:00
|
|
|
return this.map.entries();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Registry;
|