mirror of
https://github.com/tobspr/shapez.io.git
synced 2025-12-09 16:21:51 +00:00
* Update Signal * Update modal_dialogs * Inputs * Update factories * Update tracked state * Changed let to const where possible * Add HUD typings * improvements to typings * fix exports not being exposed to mods * fix signal typings * remove TypedSignal * fix all reported type errors --------- Co-authored-by: Thomas B <t.ferb1@gmail.com> Co-authored-by: EmeraldBlock <yygengjunior@gmail.com>
73 lines
1.7 KiB
TypeScript
73 lines
1.7 KiB
TypeScript
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>> = {};
|
|
|
|
constructor(public id: string) {}
|
|
|
|
getId() {
|
|
return this.id;
|
|
}
|
|
|
|
register(entry: Class<T> & { getId(): string }) {
|
|
// 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 {
|
|
return !!this.idToEntry[id];
|
|
}
|
|
|
|
/**
|
|
* Finds an instance by a given id
|
|
*/
|
|
findById(id: string): Class<T> {
|
|
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>[] {
|
|
return this.entries;
|
|
}
|
|
|
|
/**
|
|
* Returns all registered ids
|
|
*/
|
|
getAllIds(): string[] {
|
|
return this.entryIds;
|
|
}
|
|
|
|
/**
|
|
* Returns amount of stored entries
|
|
*/
|
|
getNumEntries(): number {
|
|
return this.entries.length;
|
|
}
|
|
}
|