From 4f66ecc78cf324eaec131211d84505252bcbf72d Mon Sep 17 00:00:00 2001 From: John Doe Date: Sat, 9 Sep 2023 16:52:34 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=8D=20Add=20unique=20ID=20generation?= =?UTF-8?q?=20utility?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/utils/ncNanoId.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/utils/ncNanoId.ts diff --git a/src/utils/ncNanoId.ts b/src/utils/ncNanoId.ts new file mode 100644 index 0000000..6c21384 --- /dev/null +++ b/src/utils/ncNanoId.ts @@ -0,0 +1,33 @@ +/** Used to generate unique IDs. */ +const idCounter: Record = {}; + +/** + * 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;