-
-
Notifications
You must be signed in to change notification settings - Fork 919
/
index.ts
825 lines (769 loc) · 21.9 KB
/
index.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
import type { Faker } from '../..';
import { FakerError } from '../../errors/faker-error';
import type { LiteralUnion } from '../../utils/types';
export type Casing = 'upper' | 'lower' | 'mixed';
const UPPER_CHARS: ReadonlyArray<string> = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(
''
);
const LOWER_CHARS: ReadonlyArray<string> = 'abcdefghijklmnopqrstuvwxyz'.split(
''
);
const DIGIT_CHARS: ReadonlyArray<string> = '0123456789'.split('');
export type LowerAlphaChar =
| 'a'
| 'b'
| 'c'
| 'd'
| 'e'
| 'f'
| 'g'
| 'h'
| 'i'
| 'j'
| 'k'
| 'l'
| 'm'
| 'n'
| 'o'
| 'p'
| 'q'
| 'r'
| 's'
| 't'
| 'u'
| 'v'
| 'w'
| 'x'
| 'y'
| 'z';
export type UpperAlphaChar =
| 'A'
| 'B'
| 'C'
| 'D'
| 'E'
| 'F'
| 'G'
| 'H'
| 'I'
| 'J'
| 'K'
| 'L'
| 'M'
| 'N'
| 'O'
| 'P'
| 'Q'
| 'R'
| 'S'
| 'T'
| 'U'
| 'V'
| 'W'
| 'X'
| 'Y'
| 'Z';
export type NumericChar =
| '0'
| '1'
| '2'
| '3'
| '4'
| '5'
| '6'
| '7'
| '8'
| '9';
export type AlphaChar = LowerAlphaChar | UpperAlphaChar;
export type AlphaNumericChar = AlphaChar | NumericChar;
const SAMPLE_MAX_LENGTH = 2 ** 20;
/**
* Module to generate string related entries.
*
* ### Overview
*
* For a string containing just A-Z characters, use [`alpha()`](https://fakerjs.dev/api/string.html#alpha). To add digits too, use [`alphanumeric()`](https://fakerjs.dev/api/string.html#alphanumeric). If you only want punctuation marks/symbols, use [`symbol()`](https://fakerjs.dev/api/string.html). For a full set of ASCII characters, use [`sample()`](https://fakerjs.dev/api/string.html#sample). For a custom set of characters, use [`fromCharacters()`](https://fakerjs.dev/api/string.html#fromcharacters).
*
* For strings of base-ten digits, use [`numeric()`](https://fakerjs.dev/api/string.html#numeric). For other bases, use [`binary()`](https://fakerjs.dev/api/string.html#binary), [`octal()`](https://fakerjs.dev/api/string.html#octal), or [`hexadecimal()`](https://fakerjs.dev/api/string.html#hexadecimal)).
*
* You can generate standard ID strings using [`uuid()`](https://fakerjs.dev/api/string.html#uuid) or [`nanoid()`](https://fakerjs.dev/api/string.html#nanoid).
*
* ### Related modules
*
* - Emoji can be found at [`faker.internet.emoji()`](https://fakerjs.dev/api/internet.html#emoji).
* - The [`faker.helpers`](https://fakerjs.dev/api/helpers.html) module includes a number of string related methods.
*/
export class StringModule {
constructor(private readonly faker: Faker) {
// Bind `this` so namespaced is working correctly
for (const name of Object.getOwnPropertyNames(
StringModule.prototype
) as Array<keyof StringModule | 'constructor'>) {
if (name === 'constructor' || typeof this[name] !== 'function') {
continue;
}
this[name] = this[name].bind(this);
}
}
/**
* Generates a string from the given characters.
*
* @param characters The characters to use for the string. Can be a string or an array of characters.
* If it is an array, then each element is treated as a single character even if it is a string with multiple characters.
* @param length The length of the string to generate. Defaults to `1`.
* @param length.min The minimum length of the string to generate.
* @param length.max The maximum length of the string to generate.
*
* @example
* faker.string.fromCharacters('abc') // 'c'
* faker.string.fromCharacters(['a', 'b', 'c']) // 'a'
* faker.string.fromCharacters('abc', 10) // 'cbbbacbacb'
* faker.string.fromCharacters('abc', { min: 5, max: 10 }) // 'abcaaaba'
*
* @since 8.0.0
*/
fromCharacters(
characters: string | ReadonlyArray<string>,
length:
| number
| {
/**
* The minimum length of the string to generate.
*/
min: number;
/**
* The maximum length of the string to generate.
*/
max: number;
} = 1
): string {
length = this.faker.helpers.rangeToNumber(length);
if (length <= 0) {
return '';
}
if (typeof characters === 'string') {
characters = characters.split('');
}
if (characters.length === 0) {
throw new FakerError(
'Unable to generate string: No characters to select from.'
);
}
return this.faker.helpers
.multiple(() => this.faker.helpers.arrayElement(characters as string[]), {
count: length,
})
.join('');
}
/**
* Generating a string consisting of letters in the English alphabet.
*
* @param options Either the number of characters or an options instance.
* @param options.length The number or range of characters to generate. Defaults to `1`.
* @param options.casing The casing of the characters. Defaults to `'mixed'`.
* @param options.exclude An array with characters which should be excluded in the generated string. Defaults to `[]`.
*
* @example
* faker.string.alpha() // 'b'
* faker.string.alpha(10) // 'fEcAaCVbaR'
* faker.string.alpha({ length: { min: 5, max: 10 } }) // 'HcVrCf'
* faker.string.alpha({ casing: 'lower' }) // 'r'
* faker.string.alpha({ exclude: ['W'] }) // 'Z'
* faker.string.alpha({ length: 5, casing: 'upper', exclude: ['A'] }) // 'DTCIC'
*
* @since 8.0.0
*/
alpha(
options:
| number
| {
/**
* The number or range of characters to generate.
*
* @default 1
*/
length?:
| number
| {
/**
* The minimum number of characters to generate.
*/
min: number;
/**
* The maximum number of characters to generate.
*/
max: number;
};
/**
* The casing of the characters.
*
* @default 'mixed'
*/
casing?: Casing;
/**
* An array with characters which should be excluded in the generated string.
*
* @default []
*/
exclude?: ReadonlyArray<LiteralUnion<AlphaChar>> | string;
} = {}
): string {
if (typeof options === 'number') {
options = {
length: options,
};
}
const length = this.faker.helpers.rangeToNumber(options.length ?? 1);
if (length <= 0) {
return '';
}
const { casing = 'mixed' } = options;
let { exclude = [] } = options;
if (typeof exclude === 'string') {
exclude = exclude.split('');
}
let charsArray: string[];
switch (casing) {
case 'upper':
charsArray = [...UPPER_CHARS];
break;
case 'lower':
charsArray = [...LOWER_CHARS];
break;
case 'mixed':
default:
charsArray = [...LOWER_CHARS, ...UPPER_CHARS];
break;
}
charsArray = charsArray.filter((elem) => !exclude.includes(elem));
return this.fromCharacters(charsArray, length);
}
/**
* Generating a string consisting of alpha characters and digits.
*
* @param options Either the number of characters or an options instance.
* @param options.length The number or range of characters and digits to generate. Defaults to `1`.
* @param options.casing The casing of the characters. Defaults to `'mixed'`.
* @param options.exclude An array of characters and digits which should be excluded in the generated string. Defaults to `[]`.
*
* @example
* faker.string.alphanumeric() // '2'
* faker.string.alphanumeric(5) // '3e5V7'
* faker.string.alphanumeric({ length: { min: 5, max: 10 } }) // 'muaApG'
* faker.string.alphanumeric({ casing: 'upper' }) // 'A'
* faker.string.alphanumeric({ exclude: ['W'] }) // 'r'
* faker.string.alphanumeric({ length: 5, exclude: ["a"] }) // 'x1Z7f'
*
* @since 8.0.0
*/
alphanumeric(
options:
| number
| {
/**
* The number or range of characters and digits to generate.
*
* @default 1
*/
length?:
| number
| {
/**
* The minimum number of characters and digits to generate.
*/
min: number;
/**
* The maximum number of characters and digits to generate.
*/
max: number;
};
/**
* The casing of the characters.
*
* @default 'mixed'
*/
casing?: Casing;
/**
* An array of characters and digits which should be excluded in the generated string.
*
* @default []
*/
exclude?: ReadonlyArray<LiteralUnion<AlphaNumericChar>> | string;
} = {}
): string {
if (typeof options === 'number') {
options = {
length: options,
};
}
const length = this.faker.helpers.rangeToNumber(options.length ?? 1);
if (length <= 0) {
return '';
}
const { casing = 'mixed' } = options;
let { exclude = [] } = options;
if (typeof exclude === 'string') {
exclude = exclude.split('');
}
let charsArray = [...DIGIT_CHARS];
switch (casing) {
case 'upper':
charsArray.push(...UPPER_CHARS);
break;
case 'lower':
charsArray.push(...LOWER_CHARS);
break;
case 'mixed':
default:
charsArray.push(...LOWER_CHARS, ...UPPER_CHARS);
break;
}
charsArray = charsArray.filter((elem) => !exclude.includes(elem));
return this.fromCharacters(charsArray, length);
}
/**
* Returns a [binary](https://en.wikipedia.org/wiki/Binary_number) string.
*
* @param options The optional options object.
* @param options.length The number or range of characters to generate after the prefix. Defaults to `1`.
* @param options.prefix Prefix for the generated number. Defaults to `'0b'`.
*
* @see faker.number.binary() If you would like to generate a `binary number` (within a range).
*
* @example
* faker.string.binary() // '0b1'
* faker.string.binary({ length: 10 }) // '0b1101011011'
* faker.string.binary({ length: { min: 5, max: 10 } }) // '0b11101011'
* faker.string.binary({ prefix: '0b' }) // '0b1'
* faker.string.binary({ length: 10, prefix: 'bin_' }) // 'bin_1101011011'
*
* @since 8.0.0
*/
binary(
options: {
length?:
| number
| {
/**
* The minimum number of characters to generate.
*/
min: number;
/**
* The maximum number of characters to generate.
*/
max: number;
};
prefix?: string;
} = {}
): string {
const { prefix = '0b' } = options;
let result = prefix;
result += this.fromCharacters(['0', '1'], options.length ?? 1);
return result;
}
/**
* Returns an [octal](https://en.wikipedia.org/wiki/Octal) string.
*
* @param options The optional options object.
* @param options.length The number or range of characters to generate after the prefix. Defaults to `1`.
* @param options.prefix Prefix for the generated number. Defaults to `'0o'`.
*
* @see faker.number.octal() If you would like to generate an `octal number` (within a range).
*
* @example
* faker.string.octal() // '0o3'
* faker.string.octal({ length: 10 }) // '0o1526216210'
* faker.string.octal({ length: { min: 5, max: 10 } }) // '0o15263214'
* faker.string.octal({ prefix: '0o' }) // '0o7'
* faker.string.octal({ length: 10, prefix: 'oct_' }) // 'oct_1542153414'
*
* @since 8.0.0
*/
octal(
options: {
length?:
| number
| {
/**
* The minimum number of characters to generate.
*/
min: number;
/**
* The maximum number of characters to generate.
*/
max: number;
};
prefix?: string;
} = {}
): string {
const { prefix = '0o' } = options;
let result = prefix;
result += this.fromCharacters(
['0', '1', '2', '3', '4', '5', '6', '7'],
options.length ?? 1
);
return result;
}
/**
* Returns a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) string.
*
* @param options The optional options object.
* @param options.length The number or range of characters to generate after the prefix. Defaults to `1`.
* @param options.casing Casing of the generated number. Defaults to `'mixed'`.
* @param options.prefix Prefix for the generated number. Defaults to `'0x'`.
*
* @example
* faker.string.hexadecimal() // '0xB'
* faker.string.hexadecimal({ length: 10 }) // '0xaE13d044cB'
* faker.string.hexadecimal({ length: { min: 5, max: 10 } }) // '0x7dEf7FCD'
* faker.string.hexadecimal({ prefix: '0x' }) // '0xE'
* faker.string.hexadecimal({ casing: 'lower' }) // '0xf'
* faker.string.hexadecimal({ length: 10, prefix: '#' }) // '#f12a974eB1'
* faker.string.hexadecimal({ length: 10, casing: 'upper' }) // '0xE3F38014FB'
* faker.string.hexadecimal({ casing: 'lower', prefix: '' }) // 'd'
* faker.string.hexadecimal({ length: 10, casing: 'mixed', prefix: '0x' }) // '0xAdE330a4D1'
*
* @since 8.0.0
*/
hexadecimal(
options: {
/**
* The number or range of characters to generate after the prefix.
*
* @default 1
*/
length?:
| number
| {
/**
* The minimum number of characters to generate after the prefix.
*/
min: number;
/**
* The maximum number of characters to generate after the prefix.
*/
max: number;
};
/**
* Casing of the generated number.
*
* @default 'mixed'
*/
casing?: Casing;
/**
* Prefix for the generated number.
*
* @default '0x'
*/
prefix?: string;
} = {}
): string {
const { casing = 'mixed', prefix = '0x' } = options;
const length = this.faker.helpers.rangeToNumber(options.length ?? 1);
if (length <= 0) {
return prefix;
}
let wholeString = this.fromCharacters(
[
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
'A',
'B',
'C',
'D',
'E',
'F',
],
length
);
if (casing === 'upper') {
wholeString = wholeString.toUpperCase();
} else if (casing === 'lower') {
wholeString = wholeString.toLowerCase();
}
return `${prefix}${wholeString}`;
}
/**
* Generates a given length string of digits.
*
* @param options Either the number of characters or the options to use.
* @param options.length The number or range of digits to generate. Defaults to `1`.
* @param options.allowLeadingZeros Whether leading zeros are allowed or not. Defaults to `true`.
* @param options.exclude An array of digits which should be excluded in the generated string. Defaults to `[]`.
*
* @see faker.number.int() If you would like to generate a `number` (within a range).
*
* @example
* faker.string.numeric() // '2'
* faker.string.numeric(5) // '31507'
* faker.string.numeric(42) // '06434563150765416546479875435481513188548'
* faker.string.numeric({ length: { min: 5, max: 10 } }) // '197089478'
* faker.string.numeric({ length: 42, allowLeadingZeros: false }) // '72564846278453876543517840713421451546115'
* faker.string.numeric({ length: 6, exclude: ['0'] }) // '943228'
*
* @since 8.0.0
*/
numeric(
options:
| number
| {
/**
* The number or range of digits to generate.
*
* @default 1
*/
length?:
| number
| {
/**
* The minimum number of digits to generate.
*/
min: number;
/**
* The maximum number of digits to generate.
*/
max: number;
};
/**
* Whether leading zeros are allowed or not.
*
* @default true
*/
allowLeadingZeros?: boolean;
/**
* An array of digits which should be excluded in the generated string.
*
* @default []
*/
exclude?: ReadonlyArray<LiteralUnion<NumericChar>> | string;
} = {}
): string {
if (typeof options === 'number') {
options = {
length: options,
};
}
const length = this.faker.helpers.rangeToNumber(options.length ?? 1);
if (length <= 0) {
return '';
}
const { allowLeadingZeros = true } = options;
let { exclude = [] } = options;
if (typeof exclude === 'string') {
exclude = exclude.split('');
}
const allowedDigits = DIGIT_CHARS.filter(
(digit) => !exclude.includes(digit)
);
if (
allowedDigits.length === 0 ||
(allowedDigits.length === 1 &&
!allowLeadingZeros &&
allowedDigits[0] === '0')
) {
throw new FakerError(
'Unable to generate numeric string, because all possible digits are excluded.'
);
}
let result = '';
if (!allowLeadingZeros && !exclude.includes('0')) {
result += this.faker.helpers.arrayElement(
allowedDigits.filter((digit) => digit !== '0')
);
}
result += this.fromCharacters(allowedDigits, length - result.length);
return result;
}
/**
* Returns a string containing UTF-16 chars between 33 and 125 (`!` to `}`).
*
* @param length Length of the generated string. Max length is `2^20`. Defaults to `10`.
* @param length.min The minimum number of characters to generate.
* @param length.max The maximum number of characters to generate.
*
* @example
* faker.string.sample() // 'Zo!.:*e>wR'
* faker.string.sample(5) // '6Bye8'
* faker.string.sample({ min: 5, max: 10 }) // 'FeKunG'
*
* @since 8.0.0
*/
sample(
length:
| number
| {
/**
* The minimum number of characters to generate.
*/
min: number;
/**
* The maximum number of characters to generate.
*/
max: number;
} = 10
): string {
length = this.faker.helpers.rangeToNumber(length);
if (length >= SAMPLE_MAX_LENGTH) {
length = SAMPLE_MAX_LENGTH;
}
const charCodeOption = {
min: 33,
max: 125,
};
let returnString = '';
while (returnString.length < length) {
returnString += String.fromCharCode(
this.faker.number.int(charCodeOption)
);
}
return returnString;
}
/**
* Returns a UUID v4 ([Universally Unique Identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier)).
*
* @example
* faker.string.uuid() // '4136cd0b-d90b-4af7-b485-5d1ded8db252'
*
* @since 8.0.0
*/
uuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/x/g, () => this.faker.number.hex({ min: 0x0, max: 0xf }))
.replace(/y/g, () => this.faker.number.hex({ min: 0x8, max: 0xb }));
}
/**
* Generates a [Nano ID](https://github.com/ai/nanoid).
*
* @param length Length of the generated string. Defaults to `21`.
* @param length.min The minimum length of the Nano ID to generate.
* @param length.max The maximum length of the Nano ID to generate.
*
* @example
* faker.string.nanoid() // ptL0KpX_yRMI98JFr6B3n
* faker.string.nanoid(10) // VsvwSdm_Am
* faker.string.nanoid({ min: 13, max: 37 }) // KIRsdEL9jxVgqhBDlm
*
* @since 8.0.0
*/
nanoid(
length:
| number
| {
/**
* The minimum length of the Nano ID to generate.
*/
min: number;
/**
* The maximum length of the Nano ID to generate.
*/
max: number;
} = 21
): string {
length = this.faker.helpers.rangeToNumber(length);
if (length <= 0) {
return '';
}
const generators = [
{
value: () => this.alphanumeric(1),
// a-z is 26 characters
// this times 2 for upper & lower case is 52
// add all numbers 0-9 (10 in total) you get 62
weight: 62,
},
{
value: () => this.faker.helpers.arrayElement(['_', '-']),
weight: 2,
},
];
let result = '';
while (result.length < length) {
const charGen = this.faker.helpers.weightedArrayElement(generators);
result += charGen();
}
return result;
}
/**
* Returns a string containing only special characters from the following list:
* ```txt
* ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
* ```
*
* @param length Length of the generated string. Defaults to `1`.
* @param length.min The minimum number of special characters to generate.
* @param length.max The maximum number of special characters to generate.
*
* @example
* faker.string.symbol() // '$'
* faker.string.symbol(5) // '#*!.~'
* faker.string.symbol({ min: 5, max: 10 }) // ')|@*>^+'
*
* @since 8.0.0
*/
symbol(
length:
| number
| {
/**
* The minimum number of special characters to generate.
*/
min: number;
/**
* The maximum number of special characters to generate.
*/
max: number;
} = 1
): string {
return this.fromCharacters(
[
'!',
'"',
'#',
'$',
'%',
'&',
"'",
'(',
')',
'*',
'+',
',',
'-',
'.',
'/',
':',
';',
'<',
'=',
'>',
'?',
'@',
'[',
'\\',
']',
'^',
'_',
'`',
'{',
'|',
'}',
'~',
],
length
);
}
}