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

earthnutDev / a-js-tools / 14113566943

27 Mar 2025 06:01PM UTC coverage: 90.291% (-0.4%) from 90.722%
14113566943

push

github

earthnutDev
version: 0.1.2 2025-03-28 02:01:49 删除了过去的自己

87 of 99 branches covered (87.88%)

Branch coverage included in aggregate %.

15 of 17 new or added lines in 4 files covered. (88.24%)

1 existing line in 1 file now uncovered.

99 of 107 relevant lines covered (92.52%)

6.64 hits per line

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

95.95
/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 } from 'a-type-of-js';
9
import { randomBytes } from 'crypto';
10

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

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

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

124✔
103
  /// 生成 UUID
104
  if (initOptions.type === 'uuid') {
38✔
105
    return crypto.randomUUID();
6✔
106
  }
107

108
  if (isNumber(length) && Number.isInteger(length) && length > 0) {
109
    // 验证输入参数
5✔
110
    Object.assign(initOptions, { length });
111
  }
112

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

132
  // 使用密码学安全的随机数生成器
133
  const bytes = randomBytes(initOptions.length);
134
  let result = '';
135
  /**  获取最后的 chars 数据  */
136
  const chars = templateCharsArr.join('');
137

138
  // 循环遍历
139
  bytes.forEach(byte => (result += chars.charAt(byte % chars.length)));
140

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

160
    for (let i = 0; i < maxLength; i++) {
161
      if (i < str1Length && str2[i] !== undefined) {
162
        str1[i] += str2[i];
163
      } else if (i < str2Length) {
164
        str1[i] = str2[i];
165
      }
166
    }
167
  }
168
  return result;
169
}
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