2020-05-09 14:45:23 +00:00
|
|
|
import { createLogger } from "./logging";
|
|
|
|
|
|
|
|
|
|
const logger = createLogger("factory");
|
|
|
|
|
|
|
|
|
|
// simple factory pattern
|
2023-11-17 22:02:08 +00:00
|
|
|
export class Factory<T> {
|
|
|
|
|
// Store array as well as dictionary, to speed up lookups
|
|
|
|
|
public entries: Class<T>[] = [];
|
|
|
|
|
public entryIds: string[] = [];
|
|
|
|
|
public idToEntry: Record<string, Class<T>> = {};
|
2020-05-09 14:45:23 +00:00
|
|
|
|
2023-11-17 22:02:08 +00:00
|
|
|
constructor(public id: string) {}
|
2020-05-09 14:45:23 +00:00
|
|
|
|
|
|
|
|
getId() {
|
|
|
|
|
return this.id;
|
|
|
|
|
}
|
|
|
|
|
|
2023-11-17 22:02:08 +00:00
|
|
|
register(entry: Class<T> & { getId(): string }) {
|
2020-05-09 14:45:23 +00:00
|
|
|
// Extract id
|
|
|
|
|
const id = entry.getId();
|
|
|
|
|
assert(id, "Factory: Invalid id for class: " + entry);
|
|
|
|
|
|
|
|
|
|
// Check duplicates
|
|
|
|
|
assert(!this.idToEntry[id], "Duplicate factory entry for " + id);
|
|
|
|
|
|
|
|
|
|
// Insert
|
|
|
|
|
this.entries.push(entry);
|
|
|
|
|
this.entryIds.push(id);
|
|
|
|
|
this.idToEntry[id] = entry;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Checks if a given id is registered
|
|
|
|
|
*/
|
2023-11-17 22:02:08 +00:00
|
|
|
hasId(id: string): boolean {
|
2020-05-09 14:45:23 +00:00
|
|
|
return !!this.idToEntry[id];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Finds an instance by a given id
|
|
|
|
|
*/
|
2023-11-17 22:02:08 +00:00
|
|
|
findById(id: string): Class<T> {
|
2020-05-09 14:45:23 +00:00
|
|
|
const entry = this.idToEntry[id];
|
|
|
|
|
if (!entry) {
|
|
|
|
|
logger.error("Object with id", id, "is not registered on factory", this.id, "!");
|
|
|
|
|
assert(false, "Factory: Object with id '" + id + "' is not registered!");
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return entry;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns all entries
|
|
|
|
|
*/
|
2023-11-17 22:02:08 +00:00
|
|
|
getEntries(): Class<T>[] {
|
2020-05-09 14:45:23 +00:00
|
|
|
return this.entries;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns all registered ids
|
|
|
|
|
*/
|
2023-11-17 22:02:08 +00:00
|
|
|
getAllIds(): string[] {
|
2020-05-09 14:45:23 +00:00
|
|
|
return this.entryIds;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns amount of stored entries
|
|
|
|
|
*/
|
2023-11-17 22:02:08 +00:00
|
|
|
getNumEntries(): number {
|
2020-05-09 14:45:23 +00:00
|
|
|
return this.entries.length;
|
|
|
|
|
}
|
|
|
|
|
}
|