Browse Source

🔍 Add unique ID generation utility

This commit adds a utility function for generating unique IDs with optional prefixes. It uses a counter to ensure each ID is unique and can be customized with a prefix.

This utility is useful for generating unique keys in various scenarios.

Function signature and example usage have been documented for clarity.

#id #utility #code
main
John Doe 1 year ago
parent
commit
4f66ecc78c
  1. 33
      src/utils/ncNanoId.ts

33
src/utils/ncNanoId.ts

@ -0,0 +1,33 @@
/** Used to generate unique IDs. */
const idCounter: Record<string, number> = {};
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @since 0.1.0
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @see random
* @example
*
* ncNanoId('contact_')
* // => 'contact_104'
*
* ncNanoId()
* // => '105'
*/
function ncNanoId(prefix = "ncNanoId_") {
if (!idCounter[prefix]) {
idCounter[prefix] = 0;
}
const id = ++idCounter[prefix];
if (prefix === "$lodash$") {
return `${id}`;
}
return `${prefix}${id}`;
}
export default ncNanoId;
Loading…
Cancel
Save