UNPKG

identigenium

Version:

Generate unique identifiers with configurable character sets and prefixes. Super tiny (tree-shakeable, base is 142 bytes, minified + bzipped)

34 lines (33 loc) 1.31 kB
/** * An incremental ID provider that generates unique identifiers using a specified character set * and optional prefix. IDs are generated incrementally starting from the first character * in the set, then progressing through combinations of increasing length. */ export class IncrementalIDProvider { #charSet; #prefix; idStream; /** * Creates a new IncrementalIDProvider instance. * @param permittedCharacters - A string containing all allowed characters for ID generation. MUST be a string of unique characters; this is not checked. * @param prefix - An optional prefix to prepend to all generated IDs (default: "") */ constructor(permittedCharacters, prefix = "") { this.#prefix = prefix; this.#charSet = permittedCharacters.split(""); this.idStream = this.#idGenerator(); } *#idGenerator() { //We first generate a sequence of base digits for (const baseDigit of this.#charSet) yield this.#prefix + baseDigit; //Then we append to the superdigits for (const superDigits of this.#idGenerator()) for (const baseDigit of this.#charSet) yield superDigits + baseDigit; return ""; } generateID() { return this.idStream.next().value; } }