summaryrefslogtreecommitdiff
path: root/lib/id.ts
diff options
context:
space:
mode:
authorjoonhoekim <26rote@gmail.com>2025-03-25 15:55:45 +0900
committerjoonhoekim <26rote@gmail.com>2025-03-25 15:55:45 +0900
commit1a2241c40e10193c5ff7008a7b7b36cc1d855d96 (patch)
tree8a5587f10ca55b162d7e3254cb088b323a34c41b /lib/id.ts
initial commit
Diffstat (limited to 'lib/id.ts')
-rw-r--r--lib/id.ts43
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/id.ts b/lib/id.ts
new file mode 100644
index 00000000..e6e44cbd
--- /dev/null
+++ b/lib/id.ts
@@ -0,0 +1,43 @@
+import { customAlphabet } from "nanoid"
+
+const prefixes = {
+ task: "tsk",
+}
+
+interface GenerateIdOptions {
+ /**
+ * The length of the generated ID.
+ * @default 12
+ * @example 12 => "abc123def456"
+ * */
+ length?: number
+ /**
+ * The separator to use between the prefix and the generated ID.
+ * @default "_"
+ * @example "_" => "str_abc123"
+ * */
+ separator?: string
+}
+
+/**
+ * Generates a unique ID with optional prefix and configuration.
+ * @param prefixOrOptions The prefix string or options object
+ * @param options The options for generating the ID
+ */
+export function generateId(
+ prefixOrOptions?: keyof typeof prefixes | GenerateIdOptions,
+ options: GenerateIdOptions = {}
+) {
+ if (typeof prefixOrOptions === "object") {
+ options = prefixOrOptions
+ prefixOrOptions = undefined
+ }
+
+ const { length = 12, separator = "_" } = options
+ const id = customAlphabet(
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+ length
+ )()
+
+ return prefixOrOptions ? `${prefixes[prefixOrOptions]}${separator}${id}` : id
+}