1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2025-12-10 00:31:51 +00:00
tobspr_shapez.io/src/js/core/factory.ts

73 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-05-09 14:45:23 +00:00
import { createLogger } from "./logging";
const logger = createLogger("factory");
// simple factory pattern
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
constructor(public id: string) {}
2020-05-09 14:45:23 +00:00
getId() {
return this.id;
}
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
*/
hasId(id: string): boolean {
2020-05-09 14:45:23 +00:00
return !!this.idToEntry[id];
}
/**
* Finds an instance by a given id
*/
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
*/
getEntries(): Class<T>[] {
2020-05-09 14:45:23 +00:00
return this.entries;
}
/**
* Returns all registered ids
*/
getAllIds(): string[] {
2020-05-09 14:45:23 +00:00
return this.entryIds;
}
/**
* Returns amount of stored entries
*/
getNumEntries(): number {
2020-05-09 14:45:23 +00:00
return this.entries.length;
}
}