typedash
Version:
modern, type-safe collection of utility functions
1 lines • 1.73 kB
Source Map (JSON)
{"version":3,"sources":["../../src/functions/uniqueId/uniqueId.ts"],"names":[],"mappings":";AAgCO,SAAS,SAAS,SAAS,IAAI;AACpC,QAAM,SAAS,aAAa;AAC5B,SAAO,GAAG,MAAM,GAAG,MAAM;AAC3B;AAEA,SAAS,eAAe;AACtB,MAAI,OAAO,WAAW,YAAY,OAAO,OAAO,eAAe,YAAY;AACzE,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO,iBAAiB;AAC1B;AAEA,SAAS,mBAA2B;AAClC,QAAM,SAAS,KAAK,OAAO;AAC3B,SAAO,OAAO,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE;AACxC","sourcesContent":["/**\n * Generates a unique identifier.\n *\n * If a `prefix` is provided, the resulting identifier will start with the prefix.\n * @param prefix A prefix for the identifier.\n * @returns A unique identifier.\n * @example\n * ```ts\n * uniqueId('prefix-') // 'prefix-1q2w3e4r5t'\n * ```\n */\nexport function uniqueId<Prefix extends string>(\n prefix: Prefix\n): `${Prefix}${string}`;\n/**\n * Generates a unique identifier.\n *\n * If no `prefix` is provided, the resulting identifier will not have a prefix.\n * @param prefix An optional prefix for the identifier.\n * @returns A unique identifier.\n * @example\n * ```ts\n * uniqueId() // '1q2w3e4r5t'\n * uniqueId('prefix-') // 'prefix-1q2w3e4r5t'\n * ```\n */\nexport function uniqueId(prefix?: string): string;\n/**\n * Implementation for all overloads.\n * @param prefix An optional prefix for the identifier.\n * @returns A unique identifier.\n */\nexport function uniqueId(prefix = '') {\n const suffix = generateUUID();\n return `${prefix}${suffix}`;\n}\n\nfunction generateUUID() {\n if (typeof crypto === 'object' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n\n return pseudoRandomUUID();\n}\n\nfunction pseudoRandomUUID(): string {\n const random = Math.random();\n return random.toString(36).slice(2, 11);\n}\n"]}