Help

coderljw 2024-10-13 Utils
  • Utils
  • Help
小于 1 分钟

# 1. Help

/**
 * @name 判断是否为Url
 * @example https://google.com => true
 * @example //google.com => true
 */
export const isUrl = (string: string) => {
  return /(^https?:\/\/)|(^\/\/)/.test(string)
}

/**
 * @name 字符串函数转换
 */
export const stringToFunction = <T extends (...params: any) => any>(functionString: string): T => {
  return new Function(`return ${functionString}`) as T
}

/**
 * @name 判断是否无值
 * @example 0 => false
 * @example null => true
 * @example undefined => true
 * @example NaN => true
 * @example '' => true
 * @example [] => true
 * @example {} => true
 * @example new Set() => true
 * @example new Map() => true
 * @example new Blob() => true
 */
export const isNil = (value: any) => {
  if (value === 0) return false

  if (typeof value === 'string' || Array.isArray(value)) {
    return !value.length
  }

  if (value instanceof Set || value instanceof Map || value instanceof Blob) {
    return !value.size
  }

  if (value !== null && typeof value === 'object') {
    return !Object.values(value).length
  }

  return value === null || value === void 0 || Number.isNaN(value) || !value
}

/**
 * @name 过滤对象中的空值属性
 * @example { a: 0, b: null, c: undefined, d: NaN, e: '', f: [], g: {} } => { a: 0 }
 */
export const filterNil = <T extends Record<string, any>>(obj: T): T => {
  if (typeof obj !== 'object' || obj === null) return {} as T

  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (isNil(value)) return acc
    return { ...acc, [key]: value }
  }, {} as T)
}
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
以父之名
周杰伦.mp3