summaryrefslogtreecommitdiff
path: root/lib/id.ts
blob: e6e44cbd701a253627dc21d21944042c4ad4df27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
}