-
-
Notifications
You must be signed in to change notification settings - Fork 943
/
Copy pathrandom.ts
634 lines (583 loc) · 17.3 KB
/
random.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
import type { Faker } from '.';
import { FakerError } from './errors/faker-error';
import { deprecated } from './internal/deprecated';
/**
* Method to reduce array of characters.
*
* @param arr existing array of characters
* @param values array of characters which should be removed
* @returns new array without banned characters
*/
function arrayRemove<T>(arr: T[], values: readonly T[]): T[] {
values.forEach((value) => {
arr = arr.filter((ele) => ele !== value);
});
return arr;
}
/**
* Generates random values of different kinds. Some methods are deprecated and have been moved to dedicated modules.
*/
export class Random {
constructor(private readonly faker: Faker) {
// Bind `this` so namespaced is working correctly
for (const name of Object.getOwnPropertyNames(Random.prototype)) {
if (name === 'constructor' || typeof this[name] !== 'function') {
continue;
}
this[name] = this[name].bind(this);
}
}
/**
* Returns a single random number between zero and the given max value or the given range with the specified precision.
* The bounds are inclusive.
*
* @param options Maximum value or options object.
* @param options.min Lower bound for generated number. Defaults to `0`.
* @param options.max Upper bound for generated number. Defaults to `99999`.
* @param options.precision Precision of the generated number. Defaults to `1`.
*
* @see faker.datatype.number()
*
* @example
* faker.random.number() // 55422
* faker.random.number(100) // 52
* faker.random.number({ min: 1000000 }) // 431433
* faker.random.number({ max: 100 }) // 42
* faker.random.number({ precision: 0.01 }) // 64246.18
* faker.random.number({ min: 10, max: 100, precision: 0.01 }) // 36.94
*
* @deprecated
*/
number(
options?: number | { min?: number; max?: number; precision?: number }
): number {
deprecated({
deprecated: 'faker.random.number()',
proposed: 'faker.datatype.number()',
// since: 'v5.0.0', (?)
until: 'v7.0.0',
});
return this.faker.datatype.number(options);
}
/**
* Returns a single random floating-point number for the given precision or range and precision.
*
* @param options Precision or options object.
* @param options.min Lower bound for generated number. Defaults to `0`.
* @param options.max Upper bound for generated number. Defaults to `99999`.
* @param options.precision Precision of the generated number. Defaults to `0.01`.
*
* @see faker.datatype.float()
*
* @example
* faker.random.float() // 51696.36
* faker.random.float(0.1) // 52023.2
* faker.random.float({ min: 1000000 }) // 212859.76
* faker.random.float({ max: 100 }) // 28.11
* faker.random.float({ precision: 0.1 }) // 84055.3
* faker.random.float({ min: 10, max: 100, precision: 0.001 }) // 57.315
*
* @deprecated
*/
float(
options?: number | { min?: number; max?: number; precision?: number }
): number {
deprecated({
deprecated: 'faker.random.float()',
proposed: 'faker.datatype.float()',
// since: 'v5.0.0', (?)
until: 'v7.0.0',
});
return this.faker.datatype.float(options);
}
/**
* Returns random element from the given array.
*
* @template T The type of the entries to pick from.
* @param array Array to pick the value from. Defaults to `['a', 'b', 'c']`.
*
* @example
* faker.random.arrayElement() // 'b'
* faker.random.arrayElement(['cat', 'dog', 'mouse']) // 'dog'
*/
arrayElement<T = string>(
array: ReadonlyArray<T> = ['a', 'b', 'c'] as unknown as ReadonlyArray<T>
): T {
const index =
array.length > 1
? this.faker.datatype.number({ max: array.length - 1 })
: 0;
return array[index];
}
/**
* Returns a subset with random elements of the given array in random order.
*
* @template T The type of the entries to pick from.
* @param array Array to pick the value from. Defaults to `['a', 'b', 'c']`.
* @param count Number of elements to pick.
* When not provided, random number of elements will be picked.
* When value exceeds array boundaries, it will be limited to stay inside.
*
* @example
* faker.random.arrayElements() // ['b', 'c']
* faker.random.arrayElements(['cat', 'dog', 'mouse']) // ['mouse', 'cat']
* faker.random.arrayElements([1, 2, 3, 4, 5], 2) // [4, 2]
*/
arrayElements<T>(
array: ReadonlyArray<T> = ['a', 'b', 'c'] as unknown as ReadonlyArray<T>,
count?: number
): T[] {
if (typeof count !== 'number') {
count = this.faker.datatype.number({ min: 1, max: array.length });
} else if (count > array.length) {
count = array.length;
} else if (count < 0) {
count = 0;
}
const arrayCopy = array.slice(0);
let i = array.length;
const min = i - count;
let temp: T;
let index: number;
while (i-- > min) {
index = Math.floor(
(i + 1) * this.faker.datatype.float({ min: 0, max: 0.99 })
);
temp = arrayCopy[index];
arrayCopy[index] = arrayCopy[i];
arrayCopy[i] = temp;
}
return arrayCopy.slice(min);
}
/**
* Returns a random key or value from given object.
*
* @template T The type of `Record` to pick from.
* @template K The keys of `T`.
* @param object The object to get the keys or values from.
* @param field If this is set to `'key'`, this method will a return a random key of the given instance.
* If this is set to `'value'`, this method will a return a random value of the given instance.
* Defaults to `'value'`.
*
* @example
* const object = { keyA: 'valueA', keyB: 42 };
* faker.random.objectElement(object) // 42
* faker.random.objectElement(object, 'key') // 'keyB'
* faker.random.objectElement(object, 'value') // 'valueA'
*/
objectElement<T extends Record<string, unknown>, K extends keyof T>(
object: T,
field: 'key'
): K;
objectElement<T extends Record<string, unknown>, K extends keyof T>(
object: T,
field?: unknown
): T[K];
/**
* Returns a random key or value from given object.
*
* @template T The type of `Record` to pick from.
* @template K The keys of `T`.
* @param object The object to get the keys or values from.
* @param field If this is set to `'key'`, this method will a return a random key of the given instance.
* If this is set to `'value'`, this method will a return a random value of the given instance.
* Defaults to `'value'`.
*
* @example
* const object = { keyA: 'valueA', keyB: 42 };
* faker.random.objectElement(object) // 42
* faker.random.objectElement(object, 'key') // 'keyB'
* faker.random.objectElement(object, 'value') // 'valueA'
*/
objectElement<T extends Record<string, unknown>, K extends keyof T>(
object: T,
field?: 'key' | 'value'
): K | T[K];
objectElement<T extends Record<string, unknown>, K extends keyof T>(
object = { foo: 'bar', too: 'car' } as unknown as T,
field = 'value'
): K | T[K] {
const array: Array<keyof T> = Object.keys(object);
const key = this.arrayElement(array);
return field === 'key' ? (key as K) : (object[key] as T[K]);
}
/**
* Returns a UUID v4 ([Universally Unique Identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier)).
*
* @see faker.datatype.uuid()
*
* @example
* faker.random.uuid() // '4136cd0b-d90b-4af7-b485-5d1ded8db252'
*
* @deprecated
*/
uuid(): string {
deprecated({
deprecated: 'faker.random.uuid()',
proposed: 'faker.datatype.uuid()',
// since: 'v5.0.0', (?)
until: 'v7.0.0',
});
return this.faker.datatype.uuid();
}
/**
* Returns the boolean value `true` or `false`.
*
* @see faker.datatype.boolean()
*
* @example
* faker.random.boolean() // false
*
* @deprecated
*/
boolean(): boolean {
deprecated({
deprecated: 'faker.random.boolean()',
proposed: 'faker.datatype.boolean()',
// since: 'v5.0.0', (?)
until: 'v7.0.0',
});
return this.faker.datatype.boolean();
}
/**
* Returns random word.
*
* @example
* faker.random.word() // 'Seamless'
*/
word(): string {
const wordMethods = [
this.faker.commerce.department,
this.faker.commerce.productName,
this.faker.commerce.productAdjective,
this.faker.commerce.productMaterial,
this.faker.commerce.product,
this.faker.commerce.color,
this.faker.company.catchPhraseAdjective,
this.faker.company.catchPhraseDescriptor,
this.faker.company.catchPhraseNoun,
this.faker.company.bsAdjective,
this.faker.company.bsBuzz,
this.faker.company.bsNoun,
this.faker.address.streetSuffix,
this.faker.address.county,
this.faker.address.country,
this.faker.address.state,
this.faker.finance.accountName,
this.faker.finance.transactionType,
this.faker.finance.currencyName,
this.faker.hacker.noun,
this.faker.hacker.verb,
this.faker.hacker.adjective,
this.faker.hacker.ingverb,
this.faker.hacker.abbreviation,
this.faker.name.jobDescriptor,
this.faker.name.jobArea,
this.faker.name.jobType,
];
const bannedChars = [
'!',
'#',
'%',
'&',
'*',
')',
'(',
'+',
'=',
'.',
'<',
'>',
'{',
'}',
'[',
']',
':',
';',
"'",
'"',
'_',
'-',
];
let result: string;
do {
// randomly pick from the many faker methods that can generate words
const randomWordMethod = this.arrayElement(wordMethods);
result = randomWordMethod();
} while (!result || bannedChars.some((char) => result.includes(char)));
return this.arrayElement(result.split(' '));
}
/**
* Returns string with set of random words.
*
* @param count Number of words. Defaults to a random value between `1` and `3`.
*
* @example
* faker.random.words() // 'neural'
* faker.random.words(5) // 'copy Handcrafted bus client-server Point'
*/
words(count?: number): string {
const words: string[] = [];
if (count == null) {
count = this.faker.datatype.number({ min: 1, max: 3 });
}
for (let i = 0; i < count; i++) {
words.push(this.word());
}
return words.join(' ');
}
/**
* Returns a random image url.
*
* @see faker.random.image()
*
* @example
* faker.random.image() // 'http://placeimg.com/640/480/animals'
*
* @deprecated
*/
image(): string {
deprecated({
deprecated: 'faker.random.image()',
proposed: 'faker.image.image()',
// since: 'v5.0.0', (?)
until: 'v7.0.0',
});
return this.faker.image.image();
}
/**
* Returns a random locale, that is available in this faker instance.
* You can use the returned locale with `faker.setLocale(result)`.
*
* @example
* faker.random.locale() // 'el'
*/
locale(): string {
return this.arrayElement(Object.keys(this.faker.locales));
}
/**
* Generating a string consisting of lower/upper alpha characters based on count and upcase options.
*
* @param options Either the number of characters or an options instance. Defaults to `{ count: 1, upcase: false, bannedChars: [] }`.
* @param options.count The number of characters to generate. Defaults to `1`.
* @param options.upcase If true, the result will be uppercase. If false, it will be lowercase. Defaults to `false`.
* @param options.bannedChars An array with characters to exclude. Defaults to `[]`.
*
* @example
* faker.random.alpha() // 'b'
* faker.random.alpha(10) // 'qccrabobaf'
* faker.random.alpha({ count: 5, upcase: true, bannedChars: ['a'] }) // 'DTCIC'
*/
// TODO @Shinigami92 2022-02-14: Tests covered `(count, options)`, but they were never typed like that
alpha(
options:
| number
| {
count?: number;
upcase?: boolean;
bannedChars?: readonly string[];
} = {}
): string {
if (typeof options === 'number') {
options = {
count: options,
};
}
const { count = 1, upcase = false, bannedChars = [] } = options;
let charsArray = [
'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',
];
charsArray = arrayRemove(charsArray, bannedChars);
let wholeString = '';
for (let i = 0; i < count; i++) {
wholeString += this.arrayElement(charsArray);
}
return upcase ? wholeString.toUpperCase() : wholeString;
}
/**
* Generating a string consisting of lower/upper alpha characters and digits based on count and upcase options.
*
* @param count The number of characters and digits to generate. Defaults to `1`.
* @param options The options to use. Defaults to `{ bannedChars: [] }`.
* @param options.bannedChars An array of characters and digits which should be banned in the generated string. Defaults to `[]`.
*
* @example
* faker.random.alphaNumeric() // '2'
* faker.random.alphaNumeric(5) // '3e5v7'
* faker.random.alphaNumeric(5, { bannedChars: ["a"] }) // 'xszlm'
*/
alphaNumeric(
count: number = 1,
options: { bannedChars?: readonly string[] } = {}
): string {
const { bannedChars = [] } = options;
let charsArray = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'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',
];
charsArray = arrayRemove(charsArray, bannedChars);
if (charsArray.length === 0) {
throw new FakerError(
'Unable to generate string, because all possible characters are banned.'
);
}
let wholeString = '';
for (let i = 0; i < count; i++) {
wholeString += this.arrayElement(charsArray);
}
return wholeString;
}
/**
* Generates a given length string of digits.
*
* @param length The number of digits to generate. Defaults to `1`.
* @param options The options to use. Defaults to `{}`.
* @param options.allowLeadingZeros If true, leading zeros will be allowed. Defaults to `false`.
* @param options.bannedDigits An array of digits which should be banned in the generated string. Defaults to `[]`.
*
* @example
* faker.random.numeric() // '2'
* faker.random.numeric(5) // '31507'
* faker.random.numeric(42) // '56434563150765416546479875435481513188548'
* faker.random.numeric(42, { allowLeadingZeros: true }) // '00564846278453876543517840713421451546115'
* faker.random.numeric(6, { bannedDigits: ['0'] }) // '943228'
*/
numeric(
length: number = 1,
options: {
allowLeadingZeros?: boolean;
bannedDigits?: readonly string[];
} = {}
): string {
if (length <= 0) {
return '';
}
const { allowLeadingZeros = false, bannedDigits = [] } = options;
const allowedDigits = '0123456789'
.split('')
.filter((digit) => !bannedDigits.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 banned.'
);
}
let result = '';
if (!allowLeadingZeros && !bannedDigits.includes('0')) {
result += this.arrayElement(
allowedDigits.filter((digit) => digit !== '0')
);
}
while (result.length < length) {
result += this.arrayElement(allowedDigits);
}
return result;
}
/**
* Returns a hexadecimal number.
*
* @param count Length of the generated number. Defaults to `1`.
*
* @see faker.datatype.hexadecimal()
*
* @example
* faker.random.hexaDecimal() // '0xb'
* faker.random.hexaDecimal(10) // '0xaE13F044fb'
*
* @deprecated
*/
hexaDecimal(count?: number): string {
deprecated({
deprecated: 'faker.random.hexaDecimal()',
proposed: 'faker.datatype.hexadecimal()',
// since: 'v5.0.0', (?)
until: 'v7.0.0',
});
return this.faker.datatype.hexadecimal(count);
}
/**
* Returns the result of the callback if the probability check was successful, otherwise `undefined`.
*
* @param callback The callback to that will be invoked if the probability check was successful.
* @param options The options to use. Defaults to `{}`.
* @param options.probability The probability (`[0.00, 1.00]`) of the callback being invoked. Defaults to `0.5`.
*
* @example
* faker.random.maybe(() => 'Hello World!') // 'Hello World!'
* faker.random.maybe(() => 'Hello World!', { probability: 0.1 }) // undefined
* faker.random.maybe(() => 'Hello World!', { probability: 0.9 }) // 'Hello World!'
*/
maybe<T>(
callback: () => T,
options: { probability?: number } = {}
): T | undefined {
const { probability = 0.5 } = options;
if (this.faker.datatype.float({ min: 0, max: 1 }) < probability) {
return callback();
}
return undefined;
}
}