IDGenerator
utils/id-generator.ts:33Mints short, monotonically increasing string identifiers. Used by the engine to assign ids to objects that need a stable handle for the lifetime of a world (e.g. World entities and Prefab instances).
Ids are produced by base36-encoding an internal counter that increments on
every call to IDGenerator.next. If a prefix is supplied, it is
joined to the encoded counter with an @ separator (e.g. Player@3),
making ids easier to grep for and recognise in logs.
The generator is not intended to be cryptographically random, globally
unique across processes, or stable across re-runs of a fresh generator —
two IDGenerator instances created with the same prefix will hand out the
same ids. Pair distinct prefixes with distinct generators when you need
separation, or restore a previously persisted generator by passing
IDGenerator.getState output back into the constructor.
Example
const ids = new IDGenerator({ prefix: 'Player' });
ids.next(); // 'Player@1'
ids.peek(); // 'Player@2' (does not advance)
ids.next(); // 'Player@2'
ids.count; // 2
// Round-trip through persisted state:
const resumed = new IDGenerator(ids.getState());
resumed.next(); // 'Player@3'Constructors
constructor(options: IDGeneratorOptions): IDGenerator Creates a new generator. With no arguments, ids start at 1 and have no
prefix.
Parameters
-
optionsIDGeneratorOptions
Properties
prefix?: string The prefix this generator was constructed with, or undefined if it was
created without one.
Accessors
count: number The number of ids this generator has issued so far. Equivalent to the
counter value behind the most recently returned id, and 0 for a fresh
generator that has never had IDGenerator.next called on it.
Methods
getState(): IDGeneratorOptions Captures the current state of this generator. Pass the result to a new
IDGenerator to recreate a generator that resumes issuing ids from the
same point — handy when persisting world state.
Returns
IDGeneratorOptions next(): string Advances the counter and returns the next id.
Returns
string A new id, unique within the lifetime of this generator.
peek(): string Returns the id that the next call to IDGenerator.next will produce, without advancing the counter. Useful in tests, and when an id needs to be referenced (logged, stored, displayed) before the object that will own it has finished being constructed.
Calling peek repeatedly returns the same value until next is called.
Returns
string