All files / utils isCuid2.ts

100% Statements 3/3
100% Branches 8/8
100% Functions 1/1
100% Lines 3/3

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3624x                                                   6x 6x                
const re = /^[0-9a-z]+$/
 
export interface IsCuid2Options {
  /**
   * @default 24
   */
  minLength?: number
  /**
   * @default 24
   */
  maxLength?: number
}
 
/**
 * 检测传入值是否是 Cuid2。
 *
 * @param value 要检测的值
 * @returns 返回检测结果
 * @example
 * ```typescript
 * isCuid2('1') // => false
 * isCuid2('tz4a98xxat96iws9zmbrgj3a') // => true
 * ```
 * @see https://github.com/paralleldrive/cuid2
 */
export function isCuid2(value: string, options: IsCuid2Options = {}): boolean {
  const { minLength = 24, maxLength = 24 } = options
  return (
    !!value &&
    typeof value === 'string' &&
    value.length >= minLength &&
    value.length <= maxLength &&
    re.test(value)
  )
}