• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

earthnutDev / a-js-tools / 14514117243

17 Apr 2025 10:59AM UTC coverage: 91.667% (+1.4%) from 90.291%
14514117243

push

github

earthnutDev
version: 0.3.0 2025-04-17 18:59:27 ✨ 添加了 、 用于转义字符串生成简单的正则表达式

105 of 118 branches covered (88.98%)

Branch coverage included in aggregate %.

36 of 36 new or added lines in 4 files covered. (100.0%)

1 existing line in 1 file now uncovered.

126 of 134 relevant lines covered (94.03%)

6.08 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.87
/src/getRandomString.ts
1
/**
2
 * 获取随机字符串
1✔
3
 *
1✔
4
 * @packageDocumentation
5
 * @module @a-js-tools/get-random-string
6
 * @license MIT
7
 */
8
import { isNaN, isNumber, isPlainObject, isUndefined } from 'a-type-of-js';
9

10
/**
11
 *
1✔
12
 *  随机字符串 生成器
13
 *
14
 */
15
export type RandomStringOptions = {
16
  /**
17
   * 字符串长度
18
   *
19
   * @default 32
20
   */
21
  length?: number;
22
  /**
23
   *  字符集
11✔
24
   * @default '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
25
   */
104✔
26
  chars?: string;
27
  /**
28
   *  是否包含数字
29
   *
30
   * @default false
31
   */
32
  includeNumbers?: boolean;
33
  /**
34
   *  是否包含大写字母
35
   *
36
   * @default false
37
   */
38
  includeUppercaseLetters?: boolean;
39
  /**
40
   * 是否包含特殊字符
41
   *
6✔
42
   * @default false
43
   */
5✔
44
  includeSpecial?: boolean;
45
  /**
46
   * 字符类型
47
   *
48
   * 缺省值为 'string',可选为 'uuid'
49
   *
50
   * @default 'string''
51
   */
52
  type?: 'string' | 'uuid';
53
};
54

5!
UNCOV
55
/**
×
56
 *
57
 *  获取简单的随机字符串
5✔
58
 *
59
 *  @param   options - 字符串长度
1✔
60
 *  @returns  - 随机字符串
61
 *
5✔
62
 *
4✔
63
 */
4!
64
export function getRandomString(
65
  options?: RandomStringOptions | number,
66
): string {
5✔
67
  //   验证输入参数
68
  if (
5✔
69
    // 参数类型错误
2✔
70
    (!isPlainObject(options) && !isNumber(options)) ||
71
    // 参数为 NaN
72
    (isNumber(options) && isNaN(options)) ||
5✔
73
    // 参数为数字时为无穷大
2✔
74
    (isNumber(options) && !isFinite(options)) ||
75
    // 参数为数字时为非整数
76
    (isNumber(options) && !Number.isInteger(options)) ||
5✔
77
    // 参数为数字时为负数
2✔
78
    (isNumber(options) && Number.isInteger(options) && options < 1) ||
79
    // 参数为数值然而却小于 1
80
    (isNumber(options) && options < 1) ||
5!
81
    // 参数为对象但是 length 属性非数值
82
    (isPlainObject(options) &&
83
      (!isNumber(options.length) ||
5✔
84
        options.length < 1 ||
85
        !Number.isInteger(options.length)))
5✔
86
  ) {
87
    throw new TypeError('参数类型错误 ❌ (getRandomString)');
20✔
88
  }
89

90
  const initOptions: RandomStringOptions & {
91
    length: number;
92
    chars: string;
93
    chars2: string;
94
    chars3: string;
95
  } = {
96
    length: 32,
97
    chars: 'abcdefghijklmnopqrstuvwxyz',
98
    chars2: '0123456789',
99
    chars3: '!@#$%^&*()_+~`|}{[]:;?><,./-=',
100
    type: 'string',
101
    includeUppercaseLetters: false,
102
    includeNumbers: false,
103
    includeSpecial: false,
6✔
104
  };
6✔
105

6✔
106
  /// 生成 UUID
162✔
107
  if (initOptions.type === 'uuid') {
124✔
108
    return crypto.randomUUID();
109
  }
38✔
110

6✔
111
  if (isNumber(options) && Number.isInteger(options) && options > 0) {
112
    // 验证输入参数
113
    Object.assign(initOptions, { length: options });
114
  }
5✔
115

116
  if (isPlainObject(options)) {
117
    Object.assign(initOptions, options);
118
    initOptions.length = initOptions.length < 1 ? 32 : initOptions.length;
119
  }
120
  /**  生成随机字符串  */
121
  const templateCharsArr: string[] = initOptions.chars.split('');
122
  // 添加大写字母
123
  if (initOptions.includeUppercaseLetters) {
124
    interleaveString(templateCharsArr, initOptions.chars.toUpperCase());
125
  }
126
  // 添加数字
127
  if (initOptions.includeNumbers) {
128
    interleaveString(templateCharsArr, initOptions.chars2);
129
  }
130
  // 添加特殊字符
131
  if (initOptions.includeSpecial) {
132
    interleaveString(templateCharsArr, initOptions.chars3);
133
  }
134

135
  // 使用密码学安全的随机数生成器
136
  const bytes =
137
    !isUndefined(window) && window.crypto
138
      ? window.crypto.getRandomValues(new Uint8Array(initOptions.length))
139
      : global.crypto.getRandomValues(new Uint8Array(initOptions.length));
140
  let result = '';
141
  /**  获取最后的 chars 数据  */
142
  const chars = templateCharsArr.join('');
143

144
  // 循环遍历
145
  bytes.forEach(byte => (result += chars.charAt(byte % chars.length)));
146

147
  /**
148
   *
149
   *  字符串交叉函数
150
   *
151
   *  非线形串交叉,对相交叉
152
   *
153
   *  @param  str1 - 字符串1
154
   *  @param  str2 - 字符串2
155
   *  @returns - 交叉后的字符串
156
   *  @example
157
   *  ```ts
158
   *  interleaveString('abc', '123') // 'a1b2c3'
159
   *  ```
160
   */
161
  function interleaveString(str1: string[], str2: string) {
162
    const str1Length = str1.length,
163
      str2Length = str2.length;
164
    const maxLength = Math.max(str1Length, str2Length);
165

166
    for (let i = 0; i < maxLength; i++) {
167
      if (i < str1Length && str2[i] !== undefined) {
168
        str1[i] += str2[i];
169
      } else if (i < str2Length) {
170
        str1[i] = str2[i];
171
      }
172
    }
173
  }
174
  return result;
175
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc